반응형
문제
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어 | 수신 탑(높이) |
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
문제풀이
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder());//내림차순 정렬
PriorityQueue<Integer> minQueue = new PriorityQueue<>();//오름차순정렬
for(int i = 0; i < operations.length; i++) {
String[] s = operations[i].split(" ");
//큐가 비어있을 때는 패스
if(s[0].equals("D") && maxQueue.isEmpty()) {
continue;
}
//큐에 삽입
if(s[0].equals("I")) {
maxQueue.offer(Integer.parseInt(s[1]));
minQueue.offer(Integer.parseInt(s[1]));
}
else if(s[0].equals("D") && s[1].equals("1")) {
int max = maxQueue.poll();
minQueue.remove(max);
} else {
int min = minQueue.poll();
maxQueue.remove(min);
}
}
if(maxQueue.isEmpty()) return new int[] {0,0};
else return new int[] {maxQueue.poll(), minQueue.poll()};
}
}
반응형
'알고리즘 > 프로그래머스 LV3' 카테고리의 다른 글
[프로그래머스] LV3 기지국 설치[JAVA] (0) | 2024.04.08 |
---|---|
[프로그래머스] LV3 단속카메라(JAVA) (0) | 2024.04.08 |
[프로그래머스] LV3 단어 변환(JAVA DFS 풀이) (0) | 2024.04.02 |
[프로그래머스] LV3 야근 지수(JAVA) (0) | 2024.04.02 |
[프로그래머스] LV3 정수 삼각형 (JAVA 풀이) (0) | 2024.04.01 |