프로그래머스 알고리즘 (java)
이중 우선순위 큐
코드 리뷰
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
이중 우선순위 큐가 할 연산 operations
가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return
하도록 solution
함수를 구현해주세요.
조건
명령어 | 높이 |
---|---|
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
D -1 | 큐에서 최솟값을 삭제합니다. |
풀이 방향
- string 배열을 split 하였습니다.
- 우선순위큐를 2개 만들어 오름차순 내림차순으로 초기화 시켜 사용했습니다.
- split한 String의 [0] 으로 조건을 구분해 동작 시켰습니다.
- max,min 값을 answer에 넣어 return 시켰습니다.
- 큐가 비었을때 문제가 발생해 예외조건 추가했습니다.
코드
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public int[] solution(String[] operations) {
int[] answer = {0,0};
PriorityQueue<Integer> priorityQueueWithMax = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<Integer> priorityQueueWithMin = new PriorityQueue<>();
for (String operation : operations) {
String[] splitOther = operation.split(" ");
if (splitOther[0].equals("I")) {
priorityQueueWithMax.add(Integer.parseInt(splitOther[1]));
priorityQueueWithMin.add(Integer.parseInt(splitOther[1]));
}
if (splitOther[0].equals("D")) {
if (!priorityQueueWithMax.isEmpty()) {
if (splitOther[1].equals("1")) {
int max = priorityQueueWithMax.peek();
priorityQueueWithMax.remove(max);
priorityQueueWithMin.remove(max);
} else {
int min = priorityQueueWithMin.peek();
priorityQueueWithMax.remove(min);
priorityQueueWithMin.remove(min);
}
}
}
}
if (!priorityQueueWithMax.isEmpty()) {
answer[0] = priorityQueueWithMax.peek();
answer[1] = priorityQueueWithMin.peek();
}
return answer;
}
}
느낀점
저는 우선순위큐 문제중 라면과 디스크 문제가 더 어려웠습니다. 이번 문제까지 프로그래머스에 있는 힙(heap) 문제들을 다 풀어봤는데 자료구조에 대해 많이 배운거 같습니다.
머리로 아는것과 실제로 해보는것은 역시 차이가 있다고 느꼈습니다.
취직을 한후 잊지 않고 이러한 자료구조를 이용하고 효율적인 개발을 하는 사람이 되고 싶습니다.