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

 

첫 번째 풀이

문제 설명에 나온 순서대로 구현하면 되는 문제임

코드

import java.util.*;
// k번째 수

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        
        int[] answer = new int[commands.length];
        int[] temp;
        
        // array 있고
        // commands에 [i, j, k] 여러개
        int i, j, k;
        for(int x=0; x<commands.length; x++){
            // i, j, k
            i = commands[x][0];
            j = commands[x][1];
            k = commands[x][2];
            
            // 자른 배열을 temp에 저장
            temp = new int[(j-i) + 1];
            
            // 1. array 배열의 i번째 숫자부터 j번째 숫자까지 잘라서 temp 배열에 저장
            int z = i;
            for(int y=0; y<temp.length; y++){
                temp[y] = array[z-1];
                z++;
            }
            
            // 2. 1에서 나온 배열을 정렬
            Arrays.sort(temp);
            
            // 3. k번째 수를 정답에 저장
            answer[x] = temp[k-1];
        }

		return answer;
    }
}

 

두 번째 풀이

첫 번째 풀이와 거의 비슷하게 구현함 (문제의 절차에 따른 구현)

코드

import java.util.*;
// k번째수
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        int[] temp;
        
        int i, j, k;
        int index;
        for(int x=0; x<commands.length; x++){
            // i j k
            i = commands[x][0];
            j = commands[x][1];
            k = commands[x][2];
            
            temp = new int[j-i+1];
            index = 0;
            // 1. array 잘라서 temp 배열에 저장
            for(int y=i-1; y<j; y++){
                
                temp[index++] = array[y];
            }
            
            // 2. temp 배열 정렬
            Arrays.sort(temp);
            
            // 3. temp 배열의 k번 째 숫자 answer 배열에 저장
            answer[x] = temp[k-1];
        }
        
        return answer;
    }
}

+ Recent posts