μ½”λ”© ν…ŒμŠ€νŠΈ/μžλ°”

[ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ / μžλ°” / Lv.3] 42628 μ΄μ€‘μš°μ„ μˆœμœ„ν

HHRR 2024. 7. 22. 20:43
문제

풀이

 

μ΄μ€‘μš°μ„ μˆœμœ„νλ₯Ό κ΅¬ν˜„ν•˜λŠ” 문제둜, 주어진 λͺ…령어듀을 μ²˜λ¦¬ν•˜μ—¬ μ΅œμ’…μ μœΌλ‘œ 큐의 μ΅œλŒ“κ°’κ³Ό μ΅œμ†Ÿκ°’μ„ λ°˜ν™˜ν•˜λŠ” 것이닀.

1. 두 개의 μš°μ„ μˆœμœ„ 큐 생성 (μ΅œμ†Œνž™, μ΅œλŒ€νž™)

- μ΅œλŒ€νž™ 정렬은 `Collections.reverseOrder()`둜 큐 μ—­μˆœ μ •λ ¬ν•˜μ—¬ μ΅œλŒ€νž™μ„ λ§Œλ“ λ‹€.

2. λͺ…λ Ήμ–΄ κ·œμΉ™λŒ€λ‘œ 처리

- I : min, max 두 큐에 λͺ¨λ‘ add 연산을 μˆ˜ν–‰

- D 1 : μ΅œλŒ“κ°’ μ‚­μ œ

- D -1 : μ΅œμ†Ÿκ°’ μ‚­μ œ

3. 큐가 λΉ„μ–΄μžˆμœΌλ©΄ [0, 0] λ°˜ν™˜ν•˜κ³ , λΉ„μ–΄μžˆμ§€ μ•ŠμœΌλ©΄ max.peek()으둜 μ΅œλŒ“κ°’, min.peek()둜 μ΅œμ†Ÿκ°’ λ°˜ν™˜ν•¨.

class Solution{
        public int[] solution(String[] operations) {
            PriorityQueue<Integer> min = new PriorityQueue<>();
            PriorityQueue<Integer> max = new PriorityQueue<>(Collections.reverseOrder());
            StringTokenizer st;

            for (int i=0; i<operations.length; i++){
                st = new StringTokenizer(operations[i]);
                char op = st.nextToken().charAt(0);
                int num = Integer.parseInt(st.nextToken());

                switch(op) {
                    case 'I':
                        min.add(num);
                        max.add(num);
                        break;
                    case 'D':
                        if(max.isEmpty()) break;
                        if(num == 1) {
                            int del = max.poll();
                            min.remove(del);
                        }
                        if(num == -1) {
                            int del = min.poll();
                            max.remove(del);
                        }
                }
            }

            if(max.isEmpty()) {
                return new int[] {0, 0};
            }
            return new int[] {max.peek(), min.peek()};
        }
    }