이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어 | 수신 탑(높이) |
---|---|
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
operations | return |
---|---|
["I 16","D 1"] | [0,0] |
["I 7","I 5","I -5","D -1"] | [7,5] |
16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
int[] answer = new int[2];
PriorityQueue<Integer> pq = new PriorityQueue<>();
PriorityQueue<Integer> maxPq = new PriorityQueue<>(Collections.reverseOrder());
for(String op : operations) {
StringTokenizer st = new StringTokenizer(op);
String judge = st.nextToken();
int num = Integer.parseInt(st.nextToken());
if(pq.size() < 1 && judge.equals("D"))
continue;
if(judge.equals("I")) {
pq.offer(num);
maxPq.offer(num);
continue;
}
if(num < 0) {
int min = pq.poll();
maxPq.remove(min);
continue;
}
int max = maxPq.poll();
pq.remove(max);
}
if(pq.size()>0) {
answer[0] = maxPq.peek();
answer[1] = pq.peek();
}
return answer;
}
}
1. 공백기준
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args){
String str = "이중 우선 순위"
StringTokenizer st = new StringTokenizer(str);
System.out.println(st.nextToken());
System.out.println(st.nextToken());
System.out.println(st.nextToken());
}
}
이중
우선
순위
2. 구분자 기준
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args){
String str = "이중!우선!순위"
StringTokenizer st = new StringTokenizer(str, "!", true);
int i = 1;
while(st.hasMoreTokens()) {
System.out.println((i++)+"번째 토큰: " +st.nextToken());
}
}
토크나이저 객체 생성시 세번째 인자를 true로 주면 구분자로 지정된 문자도 토큰으로 넣어준다.
1번째 토큰: 이중
2번째 토큰: !
3번째 토큰: 우선
4번째 토큰: !
5번째 토큰: 순위