📚 문제
🔎 문제해결
문제해결 시간: 2시간 이상, 방향은 잡았으나 어떤 index 값을 넣어야 하는지 모름. 레퍼런스 참고.
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
// 1. 결과를 담을 result 배열 생성. 크기는 commands.length 만큼.
int[] result = new int[commands.length];
// 2.
ArrayList list = new ArrayList();
// 3. commands 의 길이만큼 돌면서, start - 1 부터 end 전 까지의 array 를 데려옴.
// 4. 이때, start 는 commands[i] 배열의 0번째 인덱스. - 1
// 5. 이때, end 는 commands[i] 배열의 1번째 인덱스.
// 6. k에 있는 수는 commands[i] 배열의 2번째 인덱스.
for (int i = 0; i < commands.length; i ++) {
int start = commands[i][0];
int end = commands[i][1];
int k = commands[i][2];
// arr 을 시작점부터 마지막까지 잘라냄.
int [] subArray = Arrays.copyOfRange(array, start, end);
// ArrayList 로 정렬을 진행.
Arrays.sort(subArray);
// 정렬된 배열에서 인덱스 위치의 요소를 result 에 담음.
// 순회를 할 때마다, 요소를 넣어 주어야 함.
// k는 k 번째 이기 때문에, 인덱스 위치로 바꾸기 위해서는 k -1을 진행해야 함.
result[i] = subArray[k - 1];
}
return result;
}
}
💡Stream 활용.
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
// 1. 결과를 담을 result 배열 생성. 크기는 commands.length 만큼.
int[] result = new int[commands.length];
int currentElement = Arrays.Stream(array,start - 1 , end)
.sorted()
.to Array() [k - 1]
result[i] = currentElement;
}
return result;
}
'Coding Test' 카테고리의 다른 글
[Coding Test] 프로그래머스 1단계 - 푸드 파이트 대회 (0) | 2024.10.24 |
---|---|
[Coding Test] 프로그래머스 1단계 - 두 개 뽑아서 더하기 (0) | 2024.07.30 |
[Coding Test] 프로그래머스 0단계 - 주사위 게임 3 (0) | 2024.07.27 |
[Coding Test] 프로그래머스 0단계 - 분수의 덧셈 (0) | 2024.07.25 |
[Coding Test] 프로그래머스 0단계 - 옹알이(1) (0) | 2024.07.24 |