1. 🍎 문제
2. 🤔 접근
구현해야 되는 작업은 다음 3가지이다. 또한 주어진 인덱스는 1부터 시작하는 것에 주의한다.
1. 배열을 i부터 j까지 자른다.
2. 자른 배열을 정렬한다.
3. k번째 요소를 answer 배열에 추가한다.
3. 💡 구현
1. 배열 자르기
| Arrays.copyOfRange ( 원본 배열, 시작인덱스(inclusive), 끝 인덱스(exclusive) )
copyOfRange 함수를 사용하면 원하는 인덱스만큼 배열을 카피할 수 있다.
// 배열 자르기
int [] sliceArray = Arrays.copyOfRange(array, commands[t][0]-1, commands[t][1]);
2. 정렬
| Arrays.sort()
sort 함수를 사용하면 오름차순 정렬을 할 수 있다. 내리차순 정렬 같은 다른 기준의 정렬을 사용하고 싶은 경우 Comprator 또는 Comparble을 구현하면 된다.
// 오름차순 정렬
Arrays.sort(sliceArray);
3. k번째 요소 추가
int[] answer = new int[commands.length];
for(int t= 0; t< commands.length; t++){
// ... 생략
answer[t] = (sliceArray[commands[t][2]-1]);
}
4. 전체 코드
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for(int t= 0; t< commands.length; t++){
// 배열 자르기
int [] sliceArray = Arrays.copyOfRange(array, commands[t][0]-1, commands[t][1]);
// 오름차순 정렬
Arrays.sort(sliceArray);
answer[t] = (sliceArray[commands[t][2]-1]);
}
return answer;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] SQL Level 3 모음(~ing) (0) | 2024.03.01 |
---|---|
[프로그래머스] SQL Level1 모음 (0) | 2024.02.20 |
[프로그래머스] Hash : 베스트 앨범 - L3 (1) | 2024.01.10 |
[프로그래머스] 의상 : Hash - L2 (0) | 2024.01.09 |
[프로그래머스] 전화번호 목록 : Hash - L2 (1) | 2024.01.04 |