[programmers] 이중우선순위큐

KwonSC·2022년 4월 5일
0

programmers - Java

목록 보기
11/17
post-thumbnail

https://programmers.co.kr/learn/courses/30/lessons/42628


Code

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        PriorityQueue<Integer> minq = new PriorityQueue<>();
        PriorityQueue<Integer> maxq = new PriorityQueue<>(Collections.reverseOrder());
        for (String oper : operations) {
            StringTokenizer st = new StringTokenizer(oper);
            String op = st.nextToken();
            int value = Integer.parseInt(st.nextToken());
            if (op.equals("I")) {
                minq.offer(value);
                maxq.offer(value);
            }
            else if (!maxq.isEmpty()) {
                if (value == 1) {
                    int max = maxq.poll();
                    minq.remove(max);
                }
                else {
                    int min = minq.poll();
                    maxq.remove(min);
                }
            }
        }
        if (maxq.isEmpty()) {
            int[] answer = {0, 0};
            return answer;
        }
        else {
            int[] answer = {maxq.peek(), minq.peek()};
            return answer;
        }
        
    }
}

Solution

이중우선순위큐를 구현하기위해 minqmaxq를 이용해 구현하였다. 명령어가 D일때는 큐가 비었는지부터 체크후 각 큐에 맞는 값을 뺀후 나머지 큐는 remove 메소드를 통해 삭제해준다. answer를 출력할때는 큐가 비었을때는 [0, 0]을 출력하고 아닐때는 maxqminq의 루트값을 출력하면 된다.

0개의 댓글