알고리즘
프로그래머스-k번째수
송민준
2019. 10. 28. 12:24
https://programmers.co.kr/learn/courses/30/lessons/42748
코딩테스트 연습 - K번째수 | 프로그래머스
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]
programmers.co.kr
여러 값들이 들어 있는 배열의 시작 인덱스와 끝 인덱스를 받아 값을 뽑아와서 정렬 후 x번째 값을 뽑아내는 문제
이클립스에서 실행해본 코드다
class Solution {
public static void main(String args[]) {
Solution s = new Solution();
int[] array = {1, 5, 2, 6, 3, 7, 4};
int[][] commands = {{2,5,3},{4,4,1},{1,7,3}};
for(int i = 0; i < commands.length; i++) {
System.out.print(s.solution(array, commands)[i]+ " ");
}
}
public int[] solution(int[] array, int[][] commands) {
// answer를 commands 길이 만큼 크기를 선언해줌
int[] answer = new int[commands.length];
// answer index 선언
int answercount =0;
// commands 길이 만큼 반복문 실행
for(int i = 0; i < commands.length; i++) {
// temp는 시작-끝+1을 해준만큼의 길이를 선언 (ex. 5-2+1 = 4 .. 2,3,4,5)
int[] temp = new int[commands[i][1]-commands[i][0]+1];
// temp의 index 선언
int cnt = 0;
// i번째 [0]값부터 시작해서 [1]값까지
for(int j = commands[i][0]; j <= commands[i][1]; j++) {
// [0]번째 부터 시작하는데 array는 배열이므로 인덱스 값은 j-1임
temp[cnt++] = array[j-1];
}
selectionSort(temp);
// answer 배열에 temp 값을 넣어줌
answer[answercount++] = temp[commands[i][2]-1];
}
return answer;
}
// 선택정렬 메소드
public static int[] selectionSort(int[] array) {
for(int i =0; i < array.length-1; i++) {
for(int j = i; j < array.length; j++) {
if(array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
}
참고할 코드
Arrays를 활용해서 sort, copyOfRange를 활용해서 정렬, 원하는 배열의 값만 복사를 하였다.
Arrays에 대해 정리할 필요가 있음