코딩테스트
프로그래머스 k번째 수(자바) - 정렬 -> 배열 복사 주의!
leeeehhjj
2022. 4. 10. 15:34
1. 초기 코드
import java.util.*;
class Sort_1 {
int[] answer;
int count = 0;
public int[] solution(int[] array, int[][] commands) {
answer = new int[commands.length];
for (int[] command : commands) {
int i = command[0];
int j = command[1];
int k = command[2];
sort(array,i,j,k);
}
return answer;
}
public void sort(int[] array, int i, int j, int k) {
List<Integer> temp = new ArrayList<>();
for (int m = i-1; m < j; m++) {
temp.add(array[m]);
}
Collections.sort(temp);
answer[count++] = temp.get(k-1);
}
}
2. 개선 코드
: 위에서는 배열의 일부분을 정렬하는 코드를 직접 구현했지만 자바에서 배열의 일부분을 정렬할 수 있는 기능을 지원해주기 때문에 코드를 개선했다.
Arrays.sort(array이름, 시작 인덱스, 끝 인덱스+1)
예를 들어 Arrays.sort(arr, 0, 5) 이면 0부터 4까지의 배열 요소를 정렬한다.
import java.util.*;
public class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
int count = 0;
for (int[] command : commands) {
int[] duplicated = array.clone();
int i = command[0];
int j = command[1];
int k = command[2];
Arrays.sort(duplicated, i-1 , j);
answer[count++] = duplicated[i-1+k-1];
System.out.println();
}
return answer;
}
}
*여기서 주의해야 할 점은 array를 복사하는 경우이다.
처음에 int[] duplicated = array 와 같이 배열을 복사했는데 duplicated를 정렬하는 순간 array도 함께 정렬되었다.
int[] duplicated = array와 같이 적으면 duplicated라는 배열이 array의 주소를 가리키게 되기 때문이다.
따라서 배열 요소들만 복사하고 싶으면 array.clone() 처럼 써야한다.