본문 바로가기
Coding Test/Programmers

[프로그래머스] K번째수 [JAVA(자바)]

‘프로그래머스 코딩테스트 고득점 Kit’ 문제 입니다. 😀

문제 👉 <코딩테스트 연습 - K번째수 | 프로그래머스>

1. 문제

  1. 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구한다.
  2. 예를 들어, array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3

2. 풀이

정렬 을 이용한 문제 풀이

  1. Arrays.copyOfRange()를 이용해 배열을 자른다.
  2. Arrays.sort()를 이용해 정렬을 한다.

3. 코드

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++){
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }        
        return answer;
    }
}


References


🏋🏻 개인적으로 공부한 내용을 기록하고 있습니다.
잘못된 부분이 있다면 과감하게 지적해주세요!! 🏋

댓글