문제정리

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수 반환
commands 배열에 [i,j,k] 원소로 가진 2차원 배열 매개변수로 주어짐
배열을 순서대로 새면 0부터 시작하지만 i가 1이면 0번째가 1로 시작한다고 생각해야함

 

작성 코드

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 k = commands[i][2] - 1;

            int count = end - start + 1;
            int[] arr = new int[count];
            for( int j = start; j < end; j++){
                arr[count - 1] = array[j];

                count--;
            }
            Arrays.sort(arr);
            answer[i] = arr[k];
        }

        return answer;
    }
}

 

for문으로 일단 해결하긴했는데, 좀 더 분명 간략한 방법이 있을 듯

 

Arrays.copyOfRange() 메소드 사용

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.copyOfRange(array, start, end)

start는 배열에서 복사를 시작할 인덱스, end는 복사를 끝낼 인덱스로 end 직전 인덱스까지만 복사된다고 함!

 

+ Recent posts