프로그래머스 코딩테스트 연습/Level3

[프로그래머스][JAVA] 이중우선순위큐

긷뚜 2021. 5. 5. 23:08
728x90

programmers.co.kr/learn/courses/30/lessons/42628

 

코딩테스트 연습 - 이중우선순위큐

 

programmers.co.kr

PriorityQueue를 두개 만들어 하나는 내림차순으로 정렬하여

최대값을 빼야할 경우에는 내림차순으로 정렬된 Queue에서 값을 빼고

최소값을 빼야할 경우에는 오른차순으로 정렬된 Queue에서 값을 빼는 방법으로 풀었다

 

import java.util.*;
class Solution {
    public int[] solution(String[] operations) {
        PriorityQueue<Integer> hi = new PriorityQueue<>();
        PriorityQueue<Integer> ro = new PriorityQueue<>(Collections.reverseOrder());
        for(int i =0;i<operations.length;i++){
            String[] temp = operations[i].split(" ");
            if(temp[0].equals("I")){
                int iTemp = Integer.parseInt(temp[1]);
                hi.offer(iTemp);
                ro.offer(iTemp);
            }
            else{
                if(hi.size()>0){
                    if(temp[1].equals("-1")){

                        int max = hi.poll();
                        ro.remove(max);    
                    }
                    else{
                        int min = ro.poll();
                         hi.remove(min);
                    }
                }
            }
        }
        int[] answer = new int[2];

      
        if(hi.size()>=2){
            answer[0] = ro.poll();
            answer[1] = hi.poll();
        }
        else if(hi.size()==1){
            int temp = hi.poll();
            answer[0] = Math.max(temp,0);
            answer[1] = Math.min(temp,0);
        }
        return answer;
    }
    
    
}
728x90