본문 바로가기
알고리즘/프로그래머스

[프로그래머스] k번째 수 - 자바

by binghe819 2020. 7. 3.

https://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

1. 풀이


정렬을 해보는 문제이다.

 

라이브러리를 사용한다면 Arrays의 sort와 copyOfRange를 쓰면 쉽게 구할 수 있다.

 

라이브러리를 사용하지 않고 푸는 것이 중요하지만, 일단은 라이브러리를 통해 쉽게 구해보았다...

 

2. 코드


import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];

        // 명령수만큼 반복
        for(int i = 0; i < commands.length; i++){

            // 명령 가져오기 ( 인덱싱을 위한 -1 )
            int from = commands[i][0]-1;
            int to = commands[i][1];
            int k = commands[i][2]-1;

            // 슬라이싱, 정렬
            int[] tmp = Arrays.copyOfRange(array, from, to);
            Arrays.sort(tmp);
            answer[i] = tmp[k];
        }

        return answer;
    }
}

댓글