본문 바로가기
알고리즘

[프로그래머스] K번째 수 [Java/자바]

by irerin07 2019. 9. 25.
728x90

문제:https://programmers.co.kr/learn/courses/30/lessons/42748

코드:https://github.com/irerin07/AlgorithmStudyBaek/blob/master/src/programmers_lvl_1/programmers42748.java

 

import java.util.Arrays;

public class programmers42748 {
    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}};
        int[] answer = solution(array, commands);


    }

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

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

 

처음 풀이는 지금 코드와 달랐다.

범위에 해당하는 수들을 temp어레이에 일일히 담아주는 방식으로 구현했는데

다른 사람의 풀이를 보니 굉장히 좋은 방법이 있어서 사용해봤다.

 

copyOfRange(int[] original, int from, int to) 

Copies the specified range of the specified array into a new array.

원본 배열에서 지정된 범위내의 Element들을 새로운 배열에 복사해준다.

 

확실히 아는게 많으면 알고리즘 문제 풀이도 훨씬 쉬워지는것을 느낀다.

 

728x90