문제
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
- array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
- 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
- 2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한사항
- array의 길이는 1 이상 100 이하입니다.
- array의 각 원소는 1 이상 100 이하입니다.
- commands의 길이는 1 이상 50 이하입니다.
- commands의 각 원소는 길이가 3입니다.
입출력 예
array | commands | return |
[1, 5, 2, 6, 3, 7, 4] | [[2, 5, 3], [4, 4, 1], [1, 7, 3]] | [5, 6, 3] |
입출력 예 설명
[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.
풀이
1. i,j 조건에 맞게 배열을 추출
2. 추출한 배열을 오름차순으로 정렬
3. k 조건에 맞는 값을 또 다른 배열에 저장
4. 이를 커맨드 배열 길이 만큼 반복
코드
배열, sort() 사용
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
int cnt = 0;
while(cnt < commands.length) {
int i =commands[cnt][0];
int j =commands[cnt][1];
int k =commands[cnt][2];
int[] a = new int[j-i+1];
int n= 0;
for(int x=i-1; x<=j-1; x++) {
// 5263
a[n]=array[x]; // n++
n++; // 주석
}
// 정렬
Arrays.sort(a);
//System.out.println(Arrays.toString(a));
answer[cnt] = a[k-1]; // cnt++
cnt++; // 주석
}
//System.out.println(Arrays.toString(answer));
return answer;
}
}
ArrayList, Collections 사용
import java.util.Collections;
import java.util.ArrayList;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
ArrayList<Integer> list = new ArrayList<>();
for(int x=0; x < commands.length; x++) {
for(int i=commands[x][0]; i<=commands[x][1]; i++) {
list.add(array[i-1]);
Collections.sort(list);
}
//System.out.println(list);
answer[x]=list.get(commands[x][2]-1);
list.clear();
}
//System.out.println(Arrays.toString(answer));
return answer;
}
}
'코테 > 알고리즘' 카테고리의 다른 글
[ DFS / BFS ] - 게임 맵 최단거리(BFS) (1) | 2023.12.28 |
---|---|
[ DFS / BFS ] - 네트워크(DFS, BFS) (1) | 2023.12.28 |
[ DFS / BFS ] - 타겟 넘버(DFS, 재귀) (1) | 2023.12.27 |
[ 정렬 ] - H-Index(sort) (0) | 2023.12.23 |
[ 정렬 ] - 가장 큰 수(sort,compareTo,Comparator) (1) | 2023.12.22 |