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

dia·2023년 9월 22일

풀이방식

  1. 유효 구간 구하기
  2. 정렬
  3. 원하는 값만 고르기

포인트

copyOfRange

Arrays.copyOfRange(arr, indexA, indexB)
배열 arr에서 indexA부터 indexB 앞까지 잘라서 배열로 반환


구현

import java.util.Arrays;

public class NUM42748 {
    public static void main(String[] args) {
        int[] array = {1, 5, 2, 6, 3, 7, 4};
        int[][] commands = {{2, 5, 3}, {4,4,1}, {1,7,3}};
        System.out.println(Arrays.toString(solution(array, commands)));
    }
    public static int[] solution(int[] array, int[][] commands) {
        int[] answer = {};
        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;
    }
}

*다른 분들의 코드를 참고하여 작성했습니다

profile
CS 메모장

0개의 댓글