[코딩테스트] 프로그래머스 - 이중우선순위큐 (Java)

proman·2022년 9월 9일
0

Coding-Test

목록 보기
4/21
post-thumbnail

🙄 설명

레벨: 3
언어: Java

😕 느낌점

이문제는 레벨3중에서도 쉬운축에 속한문제라고 생각하는데, 푼사람들도 많고,
문제명에서도 우선순위큐로 되어있어서 우선순위큐를 사용하였습니다.
정렬순서를 최소, 최대순으로 하는 큐를 만들어서 최소값, 최대값 뽑아내는 작업을 하였고,
쩝 어려운문제는 아니라고 생각합니다...

🐧 내가작성한코드

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        Queue<Integer> maxQueue = new PriorityQueue<>((i1, i2) -> i2 - i1),
                       minQueue = new PriorityQueue<>();
        
        
        for(int i = 0; i < operations.length; i++) {
            String[] strs = operations[i].split(" ");
            if(strs[0].equals("I")) {
                minQueue.offer(Integer.valueOf(strs[1]));
                maxQueue.offer(Integer.valueOf(strs[1]));
            } else if(strs[0].equals("D") && strs[1].equals("1") && !maxQueue.isEmpty()) {
                minQueue.remove(maxQueue.poll());
            } else if(strs[0].equals("D") && strs[1].equals("-1") && !minQueue.isEmpty()) {
                maxQueue.remove(minQueue.poll());
            }
        }
        
        int min = minQueue.isEmpty() ? 0 : minQueue.poll(),
            max = maxQueue.isEmpty() ? 0 : maxQueue.poll();
        
        return new int[]{max, min} ;
    }
}

🦗 좋아요 가장많이 받은 코드

import java.util.Collections;
import java.util.PriorityQueue;

class Solution {
    public int[] solution(String[] arguments) {
        int[] answer = {0,0};

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        PriorityQueue<Integer> reverse_pq = new PriorityQueue<Integer>(Collections.reverseOrder());

        for(int i=0; i<arguments.length; i++) {
            String temp[] = arguments[i].split(" ");
            switch(temp[0]) {
            case "I" : 
                pq.add(Integer.parseInt(temp[1]));
                reverse_pq.add(Integer.parseInt(temp[1]));
                break;
            case "D" :
                if(pq.size() > 0) {
                    if(Integer.parseInt(temp[1]) == 1) {
                        // 최댓값 삭제
                        int max = reverse_pq.poll();
                        pq.remove(max);
                    } else {
                        // 최솟값 삭제
                        int min = pq.poll();
                        reverse_pq.remove(min);
                    }
                }
                break;
            }
        }

        if(pq.size() >= 2) {
            answer[0] = reverse_pq.poll();
            answer[1] = pq.poll();
        }

        System.out.println(answer[0] + ":" + answer[1]);

        return answer;
    }
}

0개의 댓글