상세 컨텐츠

본문 제목

프로그래머스_정렬_K번째수 (PriorityQueue 방식 과 QuickSort 방식) (Java)

How To Java/Algorithm Problem Solution

by 카페코더 2020. 1. 30. 19:27

본문

반응형

문제 풀이에 대한 오류 지적 및 개선 방향 제시는 항상 환영합니다.

알고리즘 문제를 엄청 잘 풀고 막 문제 보자마자 아 이거네 쉽네 ㅎㅎ 이렇게 푸는 입장이 아니라서

그 어떤 문제에 대한 비판 지적 방향제시는 언제나 감사하게 받겠습니다. 

 

문제 설명

배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.

예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면

  1. array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
  2. 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
  3. 2에서 나온 배열의 3번째 숫자는 5입니다.

배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.

제한사항

  • array의 길이는 1 이상 100 이하입니다.
  • array의 각 원소는 1 이상 100 이하입니다.
  • commands의 길이는 1 이상 50 이하입니다.
  • commands의 각 원소는 길이가 3입니다.

입출력 예

array commands return
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

입출력 예 설명

[1, 5, 2, 6, 3, 7, 4]를 2번째부터 5번째까지 자른 후 정렬합니다. [2, 3, 5, 6]의 세 번째 숫자는 5입니다.
[1, 5, 2, 6, 3, 7, 4]를 4번째부터 4번째까지 자른 후 정렬합니다. [6]의 첫 번째 숫자는 6입니다.
[1, 5, 2, 6, 3, 7, 4]를 1번째부터 7번째까지 자릅니다. [1, 2, 3, 4, 5, 6, 7]의 세 번째 숫자는 3입니다.

 

해결 방법

대학교 2학년부터 가르침을 주신 선배님께서는 "K 번째 수를 구하는 데는 퀵소트가 좋다" 라고 가르쳐 주셨다.
그래서 QuickSort 방식과 PriorityQueue를 사용한 방식 두 가지로 문제를 해결했다.

# PriorityQueue 방식

정말 간단하게 해결할 수 있다. 우선순위 큐(이하 큐)를 생성해 주고, commands의 길이 만큼 반복하여 큐를 세팅하고
K 번 만큼 값을 뽑아오면 된다.

우선순위 큐의 offer 연산의 경우 시간복잡도는 O(log n) 이며, poll의 경우 O(1) 이다. 

array commands return
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

위와 같은 상황의 시간복잡도는 다음과 같다.

A : 메인 포문의 루프 횟수
B : SetPriorityQueue 포문의 루프 횟수

A * B * log N + A로 나올 것으로 생각한다. 

Solution.Java

import java.util.PriorityQueue;

public class Programmers_Sort_1 {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        PriorityQueue<Integer> priorityQueue;

        for(int index = 0, size = commands.length ; index < size ; index++){
            priorityQueue = SetPriorityQueue(array, commands[index]);
            answer[index] = GetKnumber(priorityQueue, commands[index][2]);
        }

        return answer;
    }

    public PriorityQueue<Integer> SetPriorityQueue (int[] array, int[] commands){
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

        for(int index = commands[0] - 1, size = commands[1] ; index < size ; index++){
            priorityQueue.offer(array[index]);
        }

        return priorityQueue;
    }

    public int GetKnumber (PriorityQueue<Integer> priorityQueue, int k){
        int kNumber = 0;

        for(int index = 0 ; index < k ; index++){
            kNumber = priorityQueue.poll();
            System.out.println(kNumber);
        }

        return kNumber;
    }
}

 

# QuickSort 방식

QuickSort 의 경우 K 번째 수를 찾는데 최적화된 이유는 기준을 통하여 좌측, 우측 배열로 나뉘어 연산하기 때문이다.
아래 소스의 경우 i와 j를 기준으로 나누어 사이에 K - 1이 존재할 때 tokenArray의 K - 1번 원소를 리턴한다. 

위 방식과 다른 점은 배열이 저장되는 장소를 우선순위 큐가 아닌 ArrayList 를 사용했다는 점이다.
ArrayList 의 시간복잡도는 검색은 O(1), 추가는 O(1) or O(n) 이며,
QuickSort 의 시간복잡도는 O(n log n) ~ O(n^2) 이다.

Soultion.Java

import java.util.ArrayList;

public class Programmers_Sort_1_UsingQuickSort {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];
        ArrayList<Integer> tokenArray;

        for(int index = 0, size = commands.length ; index < size ; index++){
            tokenArray = SetArrayList(array, commands[index]);
            answer[index] = GetKNumber(tokenArray, 0, tokenArray.size() - 1, commands[index][2] - 1);
        }

        return answer;
    }

    public ArrayList<Integer> SetArrayList (int[] array, int[] commands){
        ArrayList<Integer> arrayList = new ArrayList<>();

        for(int index = commands[0] - 1, size = commands[1] ; index < size ; index++){
            arrayList.add(array[index]);
        }

        return arrayList;
    }

    public int GetKNumber (ArrayList<Integer> tokenArray, int left, int right, int k){
        int i = left;
        int j = right;
        int pivot = tokenArray.get((i + j) / 2);
        int temp;

        do{
            while (tokenArray.get(i) < pivot){
                i++;
            }
            while (tokenArray.get(j) > pivot){
                j--;
            }

            if(i <= j){
                temp = tokenArray.get(i);
                tokenArray.set(i, tokenArray.get(j));
                tokenArray.set(j, temp);
                i++;
                j--;
            }
        }while(i <= j);

        if(k > j && k < i){
            return tokenArray.get(k);
        }
        else {
            if(left < j){
                GetKNumber(tokenArray, left, j, k);
            }
            if(right > i){
                GetKNumber(tokenArray, i, right, k);
            }
        }

        return tokenArray.get(k);
    }
}

 


A와 B는 공통으로 들어가지만, 
PriorityQueue 의 경우 offer, poll 까지의 모든 연산이 같이 들어가 있으며, 
QuickSort 의 경우는 ArrayList 에 추가하는 연산과 QuickSort 자체의 연산 시간이 소요된다. 

반응형

관련글 더보기

GitHub 댓글

댓글 영역