프로그래머스/Lv.3
코딩테스트 연습 > 이중우선순위큐 - JAVA
아찌방
2024. 1. 5. 21:27
https://school.programmers.co.kr/learn/courses/30/lessons/42628
풀이 - 나의 생각
PriorityQueue를 2개 쓰면 된다.
(한개는 최솟값, 한개는 최댓값을 위한)
PriorityQueue는 기본적으로는 오름차순으로 정렬된다.
내림차순을 원한다면
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
이런식으로 해줘야 한다.
코드
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> maxQueue = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
PriorityQueue<Integer> minQueue = new PriorityQueue<>();
for(String op : operations){
String[] tmp = op.split(" ");
int num = Integer.parseInt(tmp[1]);
if(tmp[0].equals("I")){
maxQueue.offer(num);
minQueue.offer(num);
}else{
if(num == 1 && !maxQueue.isEmpty()){
int max = maxQueue.poll();
minQueue.remove(max);
}else if(!minQueue.isEmpty()){
int min = minQueue.poll();
maxQueue.remove(min);
}
}
}
int min = 0, max = 0;
if(!maxQueue.isEmpty()){
min = minQueue.poll();
max = maxQueue.poll();
}
return new int[] {max,min};
}
}
728x90