티스토리 뷰

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];
        
        // 잘라낸 숫자들
        List<Integer> cutList = new ArrayList<Integer>();
        
        for(int i=0; i<commands.length; i++) {
            
            for(int a=commands[i][0]-1; a<commands[i][1]; a++) {
                cutList.add(array[a]);
            }
            
            // 리스트 정렬하기
            Collections.sort(cutList);
            
            // k번째 숫자 배열에 넣고 리스트 비우기
            answer[i] = cutList.get(commands[i][2]-1);            
            
            cutList.clear();
        }
        
        return answer;
    }
}

 

 

다른 사람 풀이 (copyOfRange 사용)

import java.util.Arrays;

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];

        for(int i=0; i<commands.length; i++){
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }

        return answer;
    }
}
최근에 올라온 글
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Total
Today
Yesterday