[프로그래머스][K번째 수]-Lv.1

호준·2022년 11월 1일
0

Algorithm

목록 보기
89/111
post-thumbnail

🎉문제

문제링크

🎉제한사항

🎉접근방법

  1. int배열을 Integer 배열로 바꾼다.(asList를 사용하기 위해)
  2. Integer 배열을 asList를 변환 후 subList를 사용하여 List 분해
  3. 분해된 List를 정렬 후 k번 수 answer에 담기

🎉코드

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        Integer[] arr = new Integer[array.length];
        int index = 0;
        for(int i : array){
            arr[index++] = i;
        }
        int idx = 0;
        for(int[] command : commands) {
            List<Integer> list = new ArrayList<>(Arrays.asList(arr).subList(command[0] - 1, command[1]));
            Collections.sort(list);
            answer[idx++] = list.get(command[2]-1);
        }
        return answer;
    }
}

🎉알고 넘어가기

subList 는 List 는 자신이 생성된 parent 값을 가지고 있어 subList를 변경하여 parent에도 영향이 갑니다.

List<Integer> list = Arrays.asList(arr).subList(command[0] - 1, command[1]);
Collections.sort(list);
...

subList로 만들어진 list가 sort를 할 경우 부모 List인 arr List에도 영향을 미쳐 바뀝니다.

  • arr = {5,2,4,1,2};
    list = Arrays.asList(arr).subList(1,4);
    list = {2,4,1};
    list를 sort를 하게 되면 {1,2,4} 로 바뀌면,
    동시에 부모 List인 arr은 {5,1,2,4,2}로 바뀝니다.
profile
도전하지 않는 사람은 실패도 성공도 없다

0개의 댓글