[프로그래머스/Java] Lv.3 이중우선순위큐

이은정·2024년 10월 13일

프로그래머스/Java

목록 보기
56/74

문제

로직

먼저 빈 리스트를 하나 만들어준다.
그 후에 operation을 순서대로 실행하는 반복문 안에서 명령어에 따라 주어진 기능을 실행하면 된다.

코드

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        int[] answer = {};
        List<Integer> queue = new ArrayList<>();
        
        for (int i = 0; i < operations.length; i ++) {
            String[] arr = operations[i].split(" ");
            
            if (arr[0].equals("I")) {
                queue.add(Integer.parseInt(arr[1]));
            }
            else if (arr[0].equals("D") && queue.size() > 0) {
                if (Integer.parseInt(arr[1]) == 1) {
                    int max = getMax(queue);
                    queue.remove(Integer.valueOf(max));
                }
                else {
                    int min = getMin(queue);
                    
                    queue.remove(Integer.valueOf(min));
                }
            }
        }
        
        if (queue.size() == 0) {
            return new int[]{0,0};
        }
        
        int max = getMax(queue);
        int min = getMin(queue);
        
        return new int[]{max, min};
    }
    
    // queue에서 max 값 구하기
    private int getMax(List<Integer> queue) {
        return queue.stream().max(Integer::compareTo).orElseThrow();
    }
    
    // queue에서 min 값 구하기
    private int getMin(List<Integer> queue) {
        return queue.stream().min(Integer::compareTo).orElseThrow();
    }
}

결과

profile
백엔드 개발자 지망생

0개의 댓글