[프로그래머스]힙(Heap).이중우선순위큐/Java

seeun·2021년 10월 2일
0

Programmers

목록 보기
20/23
post-thumbnail

📝이중우선순위큐



✔️문제 설명

이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.

명령어수신 탑(높이)
I 숫자큐에 주어진 숫자를 삽입합니다.
D 1큐에서 최댓값을 삭제합니다.
D -1큐에서 최솟값을 삭제합니다.

이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.



✔️제한사항

  • operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
  • operations의 원소는 큐가 수행할 연산을 나타냅니다.
    - 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
  • 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.



✔️입출력 예

operationsreturn
["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;
    }
}

📎StringTokenizer

  • 컴마로 구분되는 문자열이나 특정 문자에 따라 문자열을 나누고 싶을 때 사용

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번째 토큰: 순위

profile
🤹‍♂️개발 기록 노트

0개의 댓글