알고리즘
프로그래머스 이중우선순위큐 (JAVA)
박카스마시며코딩
2021. 12. 28. 20:32
https://programmers.co.kr/learn/courses/30/lessons/42628#
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
저는 maxHeap과 minHeap 두개를 사용하여 문제를 해결하였습니다. count를 통해 실제 값이 몇개가 있는지 확인하였고, count가 0이 되면 maxHeap과 minHeap을 초기화하여 문제를 해결하였습니다.
import java.util.*;
import java.util.function.*;
class Solution {
public int[] solution(String[] operations) {
int[] answer = {};
int count = 0;
Function<String,Integer> stoi = Integer::parseInt;
PriorityQueue<Integer> maxQ = new PriorityQueue<>((o1,o2)->{
return o2 - o1;
});
PriorityQueue<Integer> minQ = new PriorityQueue<>((o1,o2)->{
return o1 - o2;
});
for(String operation : operations){
String[] temp = operation.split(" ");
int num = stoi.apply(temp[1]);
if("I".equals(temp[0])){
maxQ.offer(num);
minQ.offer(num);
count++;
}else{
if(count > 0){
count--;
if(num == 1){
System.out.println("max:"+maxQ.poll());
}else{
System.out.println("min:"+minQ.poll());
}
}
if(count == 0){
maxQ = new PriorityQueue<>((o1,o2)->{
return o2 - o1;
});
minQ = new PriorityQueue<>((o1,o2)->{
return o1 - o2;
});
}
}
}
if(count == 0){
answer = new int[]{0,0};
}else{
answer = new int[]{maxQ.poll(),minQ.poll()};
}
return answer;
}
}