티스토리 뷰

문제 링크

K번째 수

문제 조건

  • 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째 수를 구한다.
  • array의 길이는 1 이상 100 이하이다.
  • array의 각 원소는 1 이상 100 이하이다.
  • commands의 길이는 1 이상 50 이하이다.
  • commands의 각 원소는 길이가 3이다.

변수 설명

  • array : 원본 배열 (매개변수)
  • commands : [i, j, k]를 원소로 가진 2차원 배열 (매개변수)
  • Number : i, j, k를 가진 클래스
  • num : 해당 인덱스를 가지는 Number 변수
  • temp : array에서 i번째 숫자부터 j번째 숫자를 가지는 Integer 배열

코드 설명

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

Number num = new Number(commands[test_case][0], commands[test_case][1], commands[test_case][2]);
  • Number class에 commands 값을 넣어줍니다.
int[] temp = Arrays.copyOfRange(array, num.i - 1, num.j);
Arrays.sort(temp);
answer[test_case] = temp[num.k -1];
  • Arrays.copyOfRange()를 사용하여 구간을 나눕니다.
  • Arrays.sort를 이용하여 나눈 구간들을 정렬시켜줍니다.
  • answer에 정렬 된 k번 째 수를 넣어줍니다.

배운 점

  • Arrays.copyOfRange(int [] arr, int startIndex, int endIndex)
    • 배열에 원하는 구간을 잘라서 새로운 배열을 만드는 Arrays 함수
    • 1번째 매개변수 : array
    • 2번째 매개변수 : 시작하는 인덱스
    • 3번째 매개변수 : 끝나는 인덱스

문제 해답


import java.util.Arrays;

class Number {
    public int i;
    public int j;
    public int k;
    public Number(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 ln = commands.length;
        int [] answer = new int[ln];
        for(int test_case = 0 ; test_case < ln; test_case++){
            Number num = new Number(commands[test_case][0], commands[test_case][1], commands[test_case][2]);
            int[] temp = Arrays.copyOfRange(array, num.i - 1, num.j);
            Arrays.sort(temp);
            answer[test_case] = temp[num.k -1];
        }
        return answer;
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함