Coding Test/Coding Test 문제 풀이
프로그래머스 (Level 1) - K번째수
임빈영
2021. 12. 27. 11:49
문제 설명
코딩테스트 연습 - K번째수
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
풀이
commands 배열을 하나씩 탐색하면서 배열 array의 x번째부터 y번째까지의 숫자를 임시 배열인 temp에 저장했다.
저장이 끝나면 Arrays.sort() 메서드를 통해서 오름차순 정렬을 한 후, z번째에 있는 숫자를 찾아내는 방식으로 문제를 해결하였다.
전체 소스코드
import java.io.*;
import java.util.*;
public class Solution07 {
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
int[] command = commands[i];
int x = command[0] - 1; // x번째 숫자부터
int y = command[1] - 1; // y번째 숫자까지
int z = command[2] - 1; // 정렬했을 때 z번째에 있는 수
int[] temp = new int[y - x + 1];
for (int j = x; j <= y; j++) {
temp[j - x] = array[j];
}
Arrays.sort(temp);
answer[i] = temp[z];
}
return answer;
}
}
728x90