코딩테스트/프로그래머스

프로그래머스 - [Level 1]코딩테스트 연습 > 정렬 > K번째수

aiemag 2021. 3. 27. 23:14
반응형

programmers.co.kr/learn/courses/30/lessons/42748?language=java

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

Solution

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
32
33
34
35
36
37
38
39
40
41
42
43
44
//import java.util.Arrays;
 
class Solution {
    private void sortAry(int[] ary){               
        int minIdx;
        for(int i=0 ; i<ary.length-1 ; i++){
            minIdx = i;
            for(int j=i+1 ; j<ary.length ; j++){
                if(ary[minIdx] > ary[j]){
                    minIdx = j;
                }
            }
            
            if(minIdx!=i){
                int tmp = ary[minIdx];
                ary[minIdx] = ary[i];
                ary[i] = tmp;                
            }
        }
    }
    
    public int[] solution(int[] array, int[][] commands) {  
        int[] answer = new int[commands.length];     
        int from, to, k;
        for(int i=0 ; i<commands.length ; i++){            
            from = commands[i][0]-1;
            to = commands[i][1]-1;
            k = commands[i][2]-1;
            
            int cut_len = to-from+1;
            int[] cut = new int[cut_len];
            for(int j=0 ; j<cut_len ; j++){
                cut[j] = array[j+from];
            }
            
            //Arrays.sort(cut);
            sortAry(cut);
            
            answer[i] = cut[k];
        }
        
        return answer;
    }
}
cs
 

반응형