본문 바로가기

프로그래머스

프로그래머스 - K번째수

import java.util.Arrays;

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

int startIdx;
int endIdx;
int tmpLength;
int n;

int[] tmpArr;

int idx;

for (int i = 0; i < commands.length; i++) {
startIdx = commands[i][0] - 1;
endIdx = commands[i][1] - 1;
n = commands[i][2];

tmpLength = endIdx - startIdx + 1;

tmpArr = new int[tmpLength];
idx = 0;

for (int j = startIdx; j <= endIdx; j++) {
tmpArr[idx] = array[j];
idx++;
}

Arrays.sort(tmpArr);

answer[i] = tmpArr[n - 1];
}
return answer;
}
}



다른 사람 코드 - Arrays.copyOfRange(원 배열, 시작 idx, 끝 idx - 1)를 사용

기타 그 외로,, 쓸데없는 변수 선언을 줄여서 좀 더 깔끔해보인다.

import java.util.Arrays;

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

int[] tmpArr;

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

return answer;
}
}