문제
문제 풀이
문제 자체는 간단한 문제이다 array에서 값을 command에 맞게 복사해서 정렬한 후, 원하는 인덱스 값만 따로 빼와서 결과로 반환을 하면 되는 문제이다
나의 답안
public static int[] solution(int[] array, int[][] commands) {
ArrayList<Integer> answer = new ArrayList<>();
List<Integer> collect = Arrays.stream(array).boxed().collect(Collectors.toList());
for (int[] cmdArr : commands) {
int[] a = new int[cmdArr[1] - cmdArr[0] + 1];
int index = 0;
for (int i = cmdArr[0] -1 ; i < cmdArr[1]; i++) {
a[index++] = collect.get(i);
}
Arrays.sort(a);
answer.add(a[cmdArr[2] - 1]);
}
return answer.stream().mapToInt(Integer::intValue).toArray();
}
다른 답안
배열 중간에 있는 값을 빼오는데 copyOfrange 라는 함수를 사용하였다.
참고해두고 다음에 써먹도록 하자.
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for(int i=0; i<commands.length; i++){
int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);
answer[i] = temp[commands[i][2]-1];
}
return answer;
}
}
'Programmers 문제풀이 > Lv.1' 카테고리의 다른 글
2016년 (0) | 2023.03.19 |
---|---|
두 개 뽑아서 더하기 (0) | 2023.03.19 |
숫자 문자열과 영단어 (0) | 2023.03.18 |
문자열 내 마음대로 정렬하기 (0) | 2023.03.18 |
[1차] 비밀지도 (0) | 2023.03.18 |