데이터 엔지니어링 정복/Algorithm
[정렬] 프로그래머스 - K번째 수
noohhee
2021. 4. 11. 19:44
728x90
반응형
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.ArrayList;
import java.util.Collections;
class Solution {
public int[] solution(int[] array, int[][] commands) {
ArrayList<Integer> result = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
for( int i=0; i<commands.length; i++ ) {
for( int j=commands[i][0]; j<=commands[i][1]; j++ ) {
temp.add( array[j-1] );
}
Collections.sort( temp );
result.add( temp.get( commands[i][2]-1 ) );
temp.clear();
}
int[] answer = new int[ result.size() ];
for( int i=0; i<result.size(); i++ ) {
answer[i] = result.get(i);
}
return answer;
}
}
다른 사람 풀이
더보기
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
//배열 복사 메서드를 이용하여 i~j만큼 잘러서 복사하고
//복사된 배열을 정렬한다.
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;
}
}
728x90
반응형