1 minute read


입출력 예시

Input
array = [1, 5, 2, 6, 3, 7, 4]
commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
Output
[5, 6, 3]


문제 풀이

주어진 array 배열을 commands 2차원 배열의 각 [i,j,k] 별로 정해진 연산을 행해야 한다.

나름대로 접근방식을 정해보았다.

  • commands 배열의 각 [i,j,k]별로 i부터 j까지 array 배열을 자른다.
  • 자른 array 배열을 오름차순 정렬한다.
  • 정렬된 array 배열의 k번째 수를 반환할 answer 배열에 담는다.

먼저 commands 2차원 배열의 껍데기를 벗기고 안쪽 [i,j,j] 배열에 접근하자.
그리고 안쪽 반복문의 인덱스가 0이면 i, 1이면 j, 2이면 k이다.

안쪽 반복문의 인덱스가 0과 1일때는 array 배열을 i부터 j까지 잘라야한다.
조건문으로 자르기 시작할 위치 start와 끝낼 위치 end 변수를 저장한다.

배열을 어떻게 자를까?

Arrays.copyOfRange() 메서드를 통해 원본배열과 시작인덱스와 종료인덱스를 넘겨주면 원하는대로 배열을 자를 수 있다.

다음으로 안쪽 반복문의 인덱스가 2일 때는 i와 j대로 자른 array 배열(이하 split 배열)을 정렬하고 k번째 수를 알아내야 한다.
안쪽 반복분 인덱스가 2일 때 commands[i][j]의 수는 k이다.
오름차순으로 정렬된 split배열에서 commands[i][j]를 인덱스로 대입하여 k번째 수를 찾을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
for(int i=0; i<commands.length; i++) {
    for(int j=0; j<commands[i].length; j++) {
        if(j == 0) start = commands[i][j]-1;
        else if(j == 1) end = commands[i][j];
        else {
            int[] split = Arrays.copyOfRange(array, start, end);
            Arrays.sort(split);
            answer[i] = split[commands[i][j]-1];
        }   
    }
}


작성 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.*;

class Solution {
    public static void main(String[] args) {
        
        int[] array = {1,5,2,6,3,7,4};
        int[][] commands = {{2,5,3},{4,4,1},{1,7,3}};
        
        long start = System.currentTimeMillis();
        solution(array, commands);
        long end = System.currentTimeMillis();
        System.out.println("\n수행시간 = " + (end-start));
    }

    public static int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        int start = 0;
        int end = 0;

        for(int i=0; i<commands.length; i++) {
            for(int j=0; j<commands[i].length; j++) {
                if(j == 0) start = commands[i][j]-1;
                else if(j == 1) end = commands[i][j];
                else {
                    int[] split = Arrays.copyOfRange(array, start, end);
                    Arrays.sort(split);
                    answer[i] = split[commands[i][j]-1];
                }   
            }
        }
        return answer;
    }
}

회고

  • copyOfRange() 메서드를 통해 배열을 원하는대로 자를 수 있음을 알게되었다.