본문 바로가기
Algorithm/프로그래머스 코딩테스트 문제풀이전략

[프로그래머스] Lv.1 k번째 수

by 미네구스 2024. 5. 2.

https://school.programmers.co.kr/learn/courses/30/lessons/42748?language=java

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        int ans_idx = 0;
        for(int [] command: commands) {
            int start = command[0];
            int end = command[1];
            int target = command[2];
            
            int [] temp = new int[end - start + 1];
            int idx = 0;
            for(int i = start-1; i < end; i++) {
                temp[idx++] = array[i];
            }
            
            Arrays.sort(temp);
            answer[ans_idx++] = temp[target-1];
        }
        return answer;
    }
}

 

Arrays.copyOfRange를 사용한 풀이
import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        
        int ans_idx = 0;
        for(int [] command: commands) {
            int start = command[0] - 1;
            int end = command[1];
            int target = command[2] - 1;
            
            int [] temp = Arrays.copyOfRange(array, start, end);
            Arrays.sort(temp);
            answer[ans_idx++] = temp[target];
        }
        return answer;
    }
}

 

Arrays.copyOfRange(원본 배열, 시작 인덱스, 마지막 인덱스)를 하면 쉽게 배열을 복사할 수 있다.