public class kst {
public static void main(String[] args) {
int[] array = {1, 5, 2, 6, 3, 7, 4};
int[][] commands = {{2, 5, 3}, {4, 4, 1}, {1, 7, 3}};
int[] answer = solution(array, commands);
System.out.print("{ ");
for (int i = 0; i < answer.length; i++) {
System.out.print(answer[i]);
if(i!=answer.length-1) {
System.out.print(",");
}
}
System.out.println(" }");
}
private static int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
int[] arrayCopy = new int[array.length];
for (int i = 0; i < arrayCopy.length; i++) {
arrayCopy[i] = array[i];
}
for (int i = 0; i < commands.length; i++) {
for (int j = commands[i][0]-1; j < commands[i][1]; j++) {
System.out.println("commands[i][0]-1 : "+(commands[i][0]-1));
System.out.println("commands[i][1] : "+commands[i][1]);
for (int m = j+1; m < commands[i][1]; m++) {
int temp;
if(array[j]>array[m]) {
temp = array[j];
array[j] = array[m];
array[m] = temp;
}
}
System.out.print("{");
for (int j2 = 0; j2 < array.length; j2++) {
System.out.print(array[j2]);
}
System.out.print("} + ");
System.out.print("인데스 : "+(commands[i][0]+commands[i][2]-2));
System.out.println(" 값 : "+array[commands[i][0]+commands[i][2]-2]);
System.out.println("i : "+i);
answer[i] = array[commands[i][0]+commands[i][2]-2];
}
for (int j = 0; j < arrayCopy.length; j++) {
array[j] = arrayCopy[j];
}
}
return answer;
}
}
내가 푼 방법은 이러했는데.. 굉장히 시간복잡도도 높고 코드도 복잡했다.
다른 사람의 풀이를 보았는데... 정말 굉장했다.
Arrays.copyOfRange
Arrays.sort
로 배열의 잘라내기와 오름차순을 간단하게 할 수 있었다. 새로운걸 알게되었다.
하기의 풀이법 이다..
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[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
Arrays.sort(temp);
answer[i] = temp[commands[i][2]-1];
}
return answer;
}
}
'코딩테스트 연습' 카테고리의 다른 글
체육복 서로 빌려줘 수업받을 수 있는 인원 확인하는 코드 (0) | 2021.08.20 |
---|---|
일정한 형식의 답안을 제출하는 학생들중 최대 정답자명단 뽑기 (0) | 2021.08.20 |
배열내 세개의 숫자의 합이 소수인 개수 구하기. (0) | 2021.08.20 |
a,b의 내적 구하기 (0) | 2021.08.20 |
키패드에서 왼손엄지와 오른손엄지중 어느 것으로 누를지 (0) | 2021.08.19 |