자료구조&알고리즘/프로그래머스
프로그래머스 - K번째수 (JAVA)
yong_ღ'ᴗ'ღ
2023. 9. 15. 21:12
https://school.programmers.co.kr/learn/courses/30/lessons/42748
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근 방식) 원본배열을 a~b범위까지 자르고 → 자른 배열을 정렬해서 → K번째 수를 찾아야한다.
1. Arrays의 copyOfRange() 를 이용하여, 원본 배열을 잘라 arr로 새롭게 저장한다.
2. Arrays의 sort()를 이용하여, arr를 정렬한다.
3. 정렬한 arr에서 K번째 수를 찾아, 정답 배열에 넣어준다.
import java.util.Arrays;
class Solution {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
int[] arr = Arrays.copyOfRange(array, commands[i][0] - 1, commands[i][1]);
Arrays.sort(arr);
answer[i] = arr[commands[i][2] - 1];
}
return answer;
}
}