
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
'프로그래머스 > Lv.3' 카테고리의 다른 글
여행경로 - Python, dfs, stack (0) | 2024.11.18 |
---|---|
야근 지수 - Python, heap (0) | 2024.11.17 |
베스트앨범 - Python, defaultdict, sort, sorted (2) | 2024.11.06 |
네트워크 - BFS (1) | 2024.07.22 |
합승 택시 요금 - JAVA, 다익스트라 알고리즘(Dijkstra Algorithm) (0) | 2024.05.25 |