Algorithm/JAVA - 프로그래머스

프로그래머스 - K번째 수 JAVA

ㅇㅇ잉 2021. 9. 8. 02:42

C++로 풀다보니 C++구현에만 익숙해서 자바로도 풀어보려고 한다. 정렬 문제를 풀어보자

 

 

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

 

 

1.

아무것도 모르고 푼거

우우,,

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
import java.util.*;
 
 
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
 
        for(int s=0;s<commands.length; s++){
            int i = commands[s][0];
            int j = commands[s][1];
            int k = commands[s][2];
 
            int[] tmp = new int[j-i+1];
            int idx = 0;
            while(idx<tmp.length){
                tmp[idx]=array[i-1];
                idx++;
                i++;
            }
 
            Arrays.sort(tmp);
            System.out.println();
            answer[s]=tmp[k-1];
 
        }
 
 
        return answer;
    }
}
 
cs

 

 

2. 다른사람 풀이

Arrays.copyOfRange 이용해서 푼거!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.*;
 
 
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        for(int i=0;i<commands.length;i++){
            int[] tmp = Arrays.copyOfRange(array,commands[i][0]-1,commands[i][1]);
            Arrays.sort(tmp);
            answer[i]=tmp[commands[i][2]-1];
        }
        
        return answer;
    }
}
cs

깔끔하게 풀린다.