[고득점 kit] K번째 수

화낼거양's avatar
Nov 26, 2024
[고득점 kit] K번째 수
Contents
문제정답
 
 
 
 
 

문제

 
notion image
 
 
기본적으로 주어진 코드 :
 
class Solution { public int[] solution(int[] array, int[][] commands) { int[] answer = {}; return answer; } }
 
 

정답

 
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 startIndex = commands[i][0] - 1; int endIndex = commands[i][1]; // startIndex 위치부터 endIndex 위치까지의 배열 요소를 추출한 뒤, 정렬하여 반환 int[] result = Arrays.stream(Arrays.copyOfRange(array, startIndex, endIndex)).sorted().toArray(); answer[i] = result[commands[i][2] - 1]; } return answer; } }
 
 
 

코드 설명

 
초기 설정:
  • answer 배열을 명령의 길이만큼 초기화합니다.
 
int[] answer = new int[commands.length];
 
명령 반복 처리:
  • 각 명령을 처리하기 위해 for 루프를 사용합니다.
 
for (int i = 0; i < commands.length; i++) {
 
부분 배열 추출:
  • commands[i][0]commands[i][1] 값을 사용하여 부분 배열의 시작과 끝 인덱스를 설정합니다.
  • 주의할 점은 배열의 인덱스는 0부터 시작하므로, 시작 인덱스는 1을 빼줍니다.
 
int startIndex = commands[i][0] - 1; int endIndex = commands[i][1];
 
배열 자르기 및 정렬:
  • Arrays.copyOfRange(array, startIndex, endIndex)를 사용하여 부분 배열을 추출합니다.
  • Arrays.stream()을 사용하여 추출한 부분 배열을 스트림으로 변환하고, sorted()를 통해 정렬합니다.
  • 정렬된 배열을 다시 toArray()를 통해 배열로 변환합니다.
 
int[] result = Arrays.stream(Arrays.copyOfRange(array, startIndex, endIndex)).sorted().toArray();
 
특정 위치의 값 추출:
  • 정렬된 배열에서 commands[i][2] - 1에 해당하는 인덱스의 값을 answer 배열에 저장합니다.
  • 주의할 점은 배열의 인덱스가 0부터 시작하므로, 1을 빼줍니다.
 
answer[i] = result[commands[i][2] - 1];
 
결과 반환:
  • 최종적으로 모든 명령을 처리한 후 answer 배열을 반환합니다.
 
return answer;
 
 
Share article

moohyun