부호 전환
import java.util.PriorityQueue;
public class NUM42628 {
public static void main(String[] args) {
String[] operations = {"I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"};
System.out.println(Arrays.toString(solution(operations)));
}
public static int[] solution(String[] operations) {
int[] answer = {};
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
for (int i = 0; i < operations.length; i++) {
if (operations[i].charAt(0) == 'I') {
int data = Integer.parseInt(operations[i].split(" ")[1]);
minHeap.add(data);
maxHeap.add(-data);
}
else if (!minHeap.isEmpty() && operations[i].equals("D 1")) {
minHeap.remove(-maxHeap.poll());
}
else if (!minHeap.isEmpty() && operations[i].equals("D -1")) {
maxHeap.remove(-minHeap.poll());
}
}
answer = minHeap.isEmpty() ? new int[] {0, 0} : new int[] {-maxHeap.poll(), minHeap.poll()};
return answer;
}
}
Collections.reverseOrder() 이용
import java.util.Collections;
import java.util.PriorityQueue;
public class NUM42628 {
public static void main(String[] args) {
String[] operations = {"I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"};
System.out.println(Arrays.toString(solution(operations)));
}
public static int[] solution(String[] operations) {
int[] answer = {};
PriorityQueue<Integer> minHeap = new PriorityQueue();
PriorityQueue<Integer> maxHeap = new PriorityQueue(Collections.reverseOrder());
for(int i = 0; i < operations.length; i++) {
if(operations[i].charAt(0) == 'I') {
minHeap.offer(Integer.parseInt(operations[i].split(" ")[1]));
maxHeap.offer(Integer.parseInt(operations[i].split(" ")[1]));
}
else if(operations[i].equals("D 1")) { minHeap.remove(maxHeap.poll()); }
else { maxHeap.remove(minHeap.poll()); }
}
answer = minHeap.isEmpty() ? new int[]{0, 0} : new int[]{maxHeap.peek(), minHeap.peek()};
return answer;
}
}
*다른 분들의 코드를 참고하여 작성했습니다