문제
프로그래머스 문제
풀이
import java.util.*;
class Solution {
public int[] solution(final String[] operations) {
final DoublePriQue dq = new DoublePriQue();
for (final String oper : operations) {
final String[] split = oper.split(" " );
final String command = split[0];
final String number = split[1];
if (command.equals("I" )) {
dq.add(Integer.valueOf(number));
} else {
if (number.equals("1" )) {
dq.delMax();
} else {
dq.delMin();
}
}
}
if (dq.isEmpty()) {
return new int[]{0, 0};
}
return new int[]{
dq.delMax(),
dq.delMin(),
};
}
}
class DoublePriQue {
Queue<Integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder());
Queue<Integer> minQueue = new PriorityQueue<>();
Map<Integer, Integer> map = new HashMap<>();
public void add(final Integer number) {
maxQueue.add(number);
minQueue.add(number);
map.put(number, map.getOrDefault(number, 0) + 1);
}
public int delMax() {
final int rtVal = getTopValueFromQueue(maxQueue);
refreshQueue(minQueue);
return rtVal;
}
public int delMin() {
final int rtVal = getTopValueFromQueue(minQueue);
refreshQueue(maxQueue);
return rtVal;
}
private void refreshQueue(final Queue<Integer> queue) {
while (!queue.isEmpty()) {
final int numCount = map.get(queue.peek());
if (numCount > 0) {
break;
}
queue.poll();
}
}
private int getTopValueFromQueue(final Queue<Integer> queue) {
int rtVal = 0;
while (!queue.isEmpty()) {
rtVal = queue.poll();
final int numCount = map.get(rtVal);
if (numCount > 0) {
map.put(rtVal, numCount - 1);
break;
}
}
return rtVal;
}
public boolean isEmpty() {
return maxQueue.isEmpty() && minQueue.isEmpty();
}
}