본문 바로가기

프로그래머스

[프로그래머스] K번째 수

문제

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차 제출

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = {};
        int[] test = {};
       
        for(int i= 0 ; i < commands.length; i++){
            test = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(test);
            answer[i]  = test[commands[i][2]-1];
        }
       
        return answer;
    }
}

+ 배열을 자르는 함수를 구글링하여 copyOfRange에 대하여 익힌 후 문제를 풀었다.

※ Arrays.copyOfRange() 는 특정 배열의 원하는 범위만큼 복사하여 새로운 배열을 만드는 메소드

 

하지만 계속 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException 에러가 떠서 확인해보니

가장 기본적인 배열 생성 부분을 놓쳤다는 것을 알았다.

배열 공간생성을 위해 코드를 수정했다.


수정 코드

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
       
        for(int i= 0 ; i < commands.length; i++){
            int[] test = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(test);
            answer[i] = test[commands[i][2]-1];
        }
       
        return answer;
    }
}

채점 결과
    정확성: 100.0
    합계: 100.0 / 100.0

 

 

+ 배열 공부하면서 도움받은 곳

https://devmoony.tistory.com/20