만족은 하되 안주하지는 말자

기록해야 기억한다

프로그래밍/programmers&bj

[JAVA] K번째 수

D36choi 2022. 2. 10. 13:24
728x90

문제

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

내 풀이

import java.util.*;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        int index = 0;
        List<Integer> list = new ArrayList<>();
        Arrays.stream(array).forEach(i -> list.add(i));
        
        for (int[] command: commands) {
            List<Integer> subList = new ArrayList<>(list.subList(command[0]-1, command[1]));
            Collections.sort(subList);
            answer[index++] = subList.get(command[2]-1);
        }

        
        return answer;
    }
}

subList 의 주의점은 원본 리스트에 종속적이므로 새로운 리스트 객체를 생성해 할당해주는 것이 필요했다.

위처럼 ArrayList 객체를 생성해 할당하지 않으면 sort시에 원본 list에도 소팅이 적용되어 2번째 loop 부터 값이 

원하는대로 나오지 않는다.

 

알게 된 것

subList의 주의해야할 점을 알았다.

 

피드백

int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);

List 객체말고 Arrays class 를 활용해 array에 대한 값의 복사 배열을 생성할 수 있다.

위처럼 하면 List 객체들의 생성없이 단순 배열로만 해결이 가능할 것이다.

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(int[],%20int,%20int) 

 

Arrays (Java Platform SE 7 )

Sorts the specified array into ascending numerical order. Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cau

docs.oracle.com

 

'프로그래밍 > programmers&bj' 카테고리의 다른 글

[JAVA] 카카오프렌즈 컬러링북  (0) 2022.03.06
[JAVA] 문자열 압축  (0) 2022.02.21
[JAVA] 기능개발  (0) 2022.02.09
[JAVA] 완주하지 못한 선수  (0) 2022.02.09
[Python] 프로그래머스 지형 이동  (0) 2020.10.30