문제 풀이/프로그래머스

[프로그래머스] k번째 수(JAVA)

27200 2024. 4. 26. 23:06

https://school.programmers.co.kr/learn/courses/30/lessons/42748


풀이

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        ArrayList<Integer> answerArr = new ArrayList<>();
        for(int i = 0; i< commands.length; i++){
            ArrayList<Integer> tempArr = new ArrayList<>();
            for(int j = commands[i][0] -1; j <= commands[i][1] -1; j++){
                tempArr.add(array[j]);
            }
            Collections.sort(tempArr);
            answerArr.add(tempArr.get(commands[i][2] -1));
        }
        int[] answer = new int[answerArr.size()];
        for(int i = 0; i < answerArr.size(); i++){
            answer[i] = answerArr.get(i);
        }
        return answer;
    }
}

필요한 만큼만 어레이리스트에 값을 추가한 뒤에 Collections.sort로 정렬을 해준다.

그냥 리스트와 다른 점은 Collections.sort()를 이용한다는 것! Arrays.sort()가 아니다! 대신 둘 다 (,Collections.reverseOrder())을 통해 내림차순 정렬을 한다는 것은 같다.

 

이 후에는 어렵지 않게 해결 가능하다.