본문 바로가기
코딩테스트 연습

배열의 일부를 정렬하고 정렬한 수 중에 k 번째 수를 구하라.

by 고유빙글 2021. 8. 20.
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;
    }
}