
import java.util.PriorityQueue;
import java.util.Collections;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> minQue = new PriorityQueue<>();
PriorityQueue<Integer> maxQue = new PriorityQueue<>(Collections.reverseOrder());
for(String operation : operations) {
String op = operation.split(" ")[0];
int num = Integer.parseInt(operation.split(" ")[1]);
if("I".equals(op)) {
minQue.add(num);
maxQue.add(num);
}
else if("D".equals(op)) {
if(maxQue.isEmpty()) continue;
if(num == 1) {
int del = maxQue.poll();
minQue.remove(del);
} else if(num == -1) {
int del = minQue.poll();
maxQue.remove(del);
}
}
}
if(maxQue.isEmpty()) return new int[] {0,0};
return new int[] {maxQue.peek(), minQue.peek()};
}
}
이 문제는 PriorityQueue를 사용하면 간단하게 해결할 수 있다...고 한다
이중우선순위큐를 처음 들어봐서 이번 기회에 공부하고 간단하게 정리해본다
// 기본형: 우선선위가 낮은 숫자가 먼저 나옴
PriorityQueue<Integer> pQ = new PriorityQueue<>();
// 우선선위가 높은 숫자가 먼저 나옴
PriorityQueue<Integer> pQ = new PriorityQueue<>(Collections.reverseOrder());
import java.util.PriorityQueue;
public class Example {
public static void main(String[] args) {
PriorityQueue<Integer> pQ = new PriorityQueue<>();
pQ.offer(1);
pQ.offer(6);
pQ.offer(2);
while(!pQ.isEmpty()) {
System.out.println("pQ.poll() = " + pQ.poll());
}
}
}
import java.util.Comparator;
import java.util.PriorityQueue;
class Student {
int mathScore;
int engScore;
public Student(int mathScore, int engScore) {
this.mathScore = mathScore;
this.engScore = engScore;
}
}
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if(o1.mathScore == o2.mathScore) {
return o2.engScore - o1.engScore;
} else {
return o1.mathScore - o2.mathScore;
}
}
}
public class Example {
public static void main(String[] args) {
PriorityQueue<Student> pQ = new PriorityQueue<>(1, new StudentComparator());
pQ.offer(new Student(70, 50));
pQ.offer(new Student(60, 40));
pQ.offer(new Student(70, 40));
while(!pQ.isEmpty()) {
Student s = pQ.poll();
System.out.printf("Student\'s MathScore and engScore: %d, %d \n", s.mathScore, s.engScore);
}
}
}