코테/프로그래머스
프로그래머스 K번째수
65살까지 코딩
2022. 1. 16. 23:18
728x90
반응형
import java.util.ArrayList;
import java.util.Collections;
class Solution {
public int[] solution(int[] array, int[][] commands) {
//각 command 마다 하나의 결과 값이 나오므로 commands의 길이의 배열 만듦
int[] answer = new int[commands.length];
ArrayList<Integer> arrayList = new ArrayList<>();
//
for(int i =0; i<commands.length; i++){
//command의 각 숫자들을 저장
int x = commands[i][0];
int j = commands[i][1];
int k = commands[i][2];
arrayList.clear();
// x부터 j까지 배열을 자름
for(int l =x-1; l<j; l++ ){
arrayList.add(array[l]);
}
//자른 배열을 정렬시킴
Collections.sort(arrayList);
//k번쨰에 있는 수를 answer에 저장시킴
answer[i] = arrayList.get(k-1);
}
return answer;
}
}
출처: https://programmers.co.kr/learn/courses/30/lessons/42748
코딩테스트 연습 - K번째수
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
728x90
반응형