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.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 start = commands[i][0]-1;
int end = commands[i][1]-1;
int thnum = commands[i][2]-1;
int[] temp = new int[end - start + 1];
for(int t = 0; t < temp.length; t++){
temp[t] = array[t+start];
}
Arrays.sort(temp);
answer[i] = temp[thnum];
}
return answer;
}
}
그러다가 다른 사람이 짠 코드를 살펴보았는데 Arrays 클래스에 이런 메소드가 있는지 이제 알았다..
// 다른 사람 코드
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;
}
}
[배운 것]
* Arrays.copyOrRange(arr, start, end) : start~end-1까지의 부분 배열을 리턴함
- 여기서 복사되는 배열은 start~end-1까지이다.
- 파이썬의 range 함수와 비슷한 개념이라고 보면 될 듯
'Study Log > Algorithm' 카테고리의 다른 글
Programmers / Hash - 베스트 앨범 (0) | 2021.08.29 |
---|---|
Programmers / 정렬 - 가장 큰 수 (0) | 2021.04.18 |
Programmers / Hash - 완주하지 못한 선수 (0) | 2021.04.06 |
카카오 2020 블라인드 채용 1차 코딩테스트 4번 문제 - 가사 검색 (0) | 2020.09.11 |
카카오 2020 블라인드 채용 1차 코딩테스트 3번 문제 - 자물쇠와 열쇠 (0) | 2020.09.07 |
댓글