본문 바로가기
프로그래머스/[프로그래머스 - JAVA] Lv.1

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

by 코딩하는 흰둥이 2023. 4. 4.
반응형


  • 내 풀이
import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = {};
        
        answer = new int[3];

        for (int i = 0; i < commands.length; i++) {
            int start = commands[i][0]-1;
            int end = commands[i][1];
            int middle = commands[i][2];
            int[] check = new int[end-start];
            for (int j = 0; j < check.length; j++) {
                check[j] = array[j+start];
            }
            Arrays.sort(check);
            answer[i] = check[middle-1];
        }
        return answer;
    }
}

실행은 성공 --> 제출 후 채점하기는 실패

뭐가 문제인지 하나씩 바꿔보다가 answer = new int[3] 이 문제라는 걸 알게 되었음

 

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = {};
		// commands의 개수 만큼 숫자가 나옴
        answer = new int[commands.length];

        for (int i = 0; i < commands.length; i++) {
        	// 굳이 변수에 담지 않아도 되는데 일일이 쓰기 귀찮아서 담아둠
            // [0][0] 에서 [0][1] 까지의 숫자를 가져와야하는데 -1을 하지 않으면 본인을 포함하지 않게 된다
            int start = commands[i][0]-1;
            int end = commands[i][1];
            int middle = commands[i][2];
            
            int[] check = new int[end-start];
            for (int j = 0; j < check.length; j++) {
                check[j] = array[j+start];
            }
            //정렬한 숫자에서 [0][2] 번째의 숫자를 불러와야함
            Arrays.sort(check);
            // 배열에 있기 때문에 -1해줘야함
            answer[i] = check[middle-1];
        }
        return answer;
    }
}

 

  • 다른 사람 풀이
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[] 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를 저렇게 쓰는거구나

댓글