Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

발전하는 개발자가 되자

프로그래머스 알고리즘 : 이중 우선순위 큐 (java) 본문

개발공부/알고리즘

프로그래머스 알고리즘 : 이중 우선순위 큐 (java)

백경훈 2019. 3. 12. 17:09

프로그래머스 알고리즘 (java)

이중 우선순위 큐

프로그래머스 (이중 우선순위 큐)

코드 리뷰

이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.

이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.

조건

명령어 높이
I 숫자 큐에 주어진 숫자를 삽입합니다.
D 1 큐에서 최댓값을 삭제합니다.
D -1 큐에서 최솟값을 삭제합니다.

풀이 방향

  1. string 배열을 split 하였습니다.
  2. 우선순위큐를 2개 만들어 오름차순 내림차순으로 초기화 시켜 사용했습니다.
  3. split한 String의 [0] 으로 조건을 구분해 동작 시켰습니다.
  4. max,min 값을 answer에 넣어 return 시켰습니다.
  5. 큐가 비었을때 문제가 발생해 예외조건 추가했습니다.

코드

import java.util.Comparator;
import java.util.PriorityQueue;

class Solution {
    public int[] solution(String[] operations) {
        int[] answer = {0,0};
        PriorityQueue<Integer> priorityQueueWithMax = new PriorityQueue<>(Comparator.reverseOrder());
        PriorityQueue<Integer> priorityQueueWithMin = new PriorityQueue<>();

        for (String operation : operations) {
            String[] splitOther = operation.split(" ");

            if (splitOther[0].equals("I")) {
                priorityQueueWithMax.add(Integer.parseInt(splitOther[1]));
                priorityQueueWithMin.add(Integer.parseInt(splitOther[1]));
            }

            if (splitOther[0].equals("D")) {
                if (!priorityQueueWithMax.isEmpty()) {
                    if (splitOther[1].equals("1")) {
                        int max = priorityQueueWithMax.peek();
                        priorityQueueWithMax.remove(max);
                        priorityQueueWithMin.remove(max);

                    } else {
                        int min = priorityQueueWithMin.peek();
                        priorityQueueWithMax.remove(min);
                        priorityQueueWithMin.remove(min);
                    }
                }
            }

        }
        if (!priorityQueueWithMax.isEmpty()) {
            answer[0] = priorityQueueWithMax.peek();
            answer[1] = priorityQueueWithMin.peek();

        }
        return answer;
    }
}

느낀점

저는 우선순위큐 문제중 라면과 디스크 문제가 더 어려웠습니다. 이번 문제까지 프로그래머스에 있는 힙(heap) 문제들을 다 풀어봤는데 자료구조에 대해 많이 배운거 같습니다. 머리로 아는것과 실제로 해보는것은 역시 차이가 있다고 느꼈습니다.
취직을 한후 잊지 않고 이러한 자료구조를 이용하고 효율적인 개발을 하는 사람이 되고 싶습니다.


Comments