[Programmers] K번째수 - JAVA

ONE·2022년 3월 21일
0

Programmers

목록 보기
17/24

📚 Problem

K번째수

  • 배열 arrayi번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하기

📝 Solution

Key Idea

  • Arrays.copyOfRange 를 이용해 i번째부터 j번째까지의 배열을 구합니다
  • Arrays.sort 를 이용해 배열을 오름차순으로 정렬하고 k 번째 인덱스의 값을 구합니다
    private int find(Command command, int[] array) {
        int[] subArray = Arrays.copyOfRange(array, command.i - 1, command.j);

        Arrays.sort(subArray);

        return subArray[command.k - 1];
    }

💻 Code

Solution.java

import java.util.ArrayList;
import java.util.Arrays;

class Command {
    int i;
    int j;
    int k;

    public Command(int i, int j, int k) {
        this.i = i;
        this.j = j;
        this.k = k;
    }
}

class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer;
        ArrayList<Command> list = new ArrayList<>();

        for (int[] command : commands)
            list.add(new Command(command[0], command[1], command[2]));

        answer = new int[list.size()];

        for(int i = 0; i < answer.length; i++)
            answer[i] = find(list.get(i), array);

        return answer;
    }

    private int find(Command command, int[] array) {
        int[] subArray = Arrays.copyOfRange(array, command.i - 1, command.j);

        Arrays.sort(subArray);

        return subArray[command.k - 1];
    }
}

SolutionTest.java

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

public class SolutionTest {
    Solution solution;

    @BeforeEach
    public void setSol(){
        solution = new Solution();
    }

    @Test
    public void solution_1(){
        int[] result = solution.solution(new int[]{1, 5, 2, 6, 3, 7, 4}, new int[][]{{2,5,3},{4,4,1},{1,7,3}});
        assertArrayEquals(new int[]{5,6,3}, result);
    }
}

profile
New, Strange, Want to try

0개의 댓글