💡Problem Solving/Programmers
[프로그래머스] 이중우선순위큐 (Java)
gom20
2021. 11. 3. 23:21
문제
https://programmers.co.kr/learn/courses/30/lessons/42628#
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
풀이
최소힙, 최대힙을 각각 두 개 만들어서 풀었다.
size가 0이 되었을 때는 큐를 clear 해줘야한다.
안 그러면 일부 남은 데이터로 인해 오류가 발생한다.
소스코드
import java.util.*;
class CustomQueue{
int size;
PriorityQueue<Integer> minHeap;
PriorityQueue<Integer> maxHeap;
public CustomQueue(){
this.size = 0;
this.minHeap = new PriorityQueue<Integer>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b){
return a-b;
}
});
this.maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b){
return b-a;
}
});
}
public void offer(int num){
minHeap.offer(num);
maxHeap.offer(num);
size++;
}
public void removeMaxVal(){
if(isEmpty()) return;
maxHeap.poll();
size--;
clear();
}
public void removeMinVal(){
if(isEmpty()) return;
minHeap.poll();
size--;
clear();
}
public void clear(){
if(size == 0){
minHeap.clear();
maxHeap.clear();
}
}
public boolean isEmpty(){
if(size == 0) return true;
return false;
}
}
class Solution {
public int[] solution(String[] operations) {
int[] answer = {};
CustomQueue que = new CustomQueue();
for(int i = 0; i < operations.length; i++){
String s = operations[i];
if("D 1".equals(s)){
que.removeMaxVal();
} else if("D -1".equals(s)){
que.removeMinVal();
} else {
que.offer(Integer.parseInt(s.split(" ")[1]));
}
}
if(que.isEmpty()) return new int[]{0, 0};
return new int[]{que.maxHeap.peek(), que.minHeap.peek()};
}
}