프로그래머스 - 이중우선순위큐 (Java)

2025. 3. 4. 13:55·알고리즘
728x90

먼저 이중우선순위큐를 구현하기 위해서 유의해야 할 점

매번 정렬을 하는 것은 비효율적 (시간초과 문제)

 

풀이 1. 우선순위 큐 2개 (최대힙과 최소힙) 구현

PriorityQueue : 중복값 허용. 삭제 시 중복값 존재하는 경우, 우선순위가 높은 값 하나만 삭제.

import java.util.*;

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

        PriorityQueue<Integer> minQ = new PriorityQueue<>();
        PriorityQueue<Integer> maxQ = new PriorityQueue<>(Collections.reverseOrder());


        for(String cur : operations){
            String[] tmp = cur.split(" ");
            if(tmp[0].equals("I")) {
                Integer x = Integer.parseInt(tmp[1]);
                maxQ.add(x);
                minQ.add(x);
            } else {
                if(maxQ.isEmpty()) continue;
                if(tmp[1].equals("1")) minQ.remove(maxQ.poll());
                else maxQ.remove(minQ.poll());
            }
        }

        if(!maxQ.isEmpty()) {
            answer[0] = maxQ.poll();
            answer[1] = minQ.poll();
        }

        return answer;
    }
}

 

풀이 2. TreeMap 구현

TreeMap의 경우, 원소를 삽입하면 자동 정렬이 되므로 HashMap보다 느리지만, 순서 유지가 필요할 때 유용.

 

lastEntry(): 가장 뒤에 있는 key-value 쌍을 가져올 수 있음

firstEntry(): 가장 앞에 있는 key-value 쌍을 가져올 수 있음

 

getOrDefault()를 사용하여 value를 늘려주는 방식으로 중복값 구현 가능.

만약 값을 삭제하려고 할 때 value가 1이면 완전 삭제를, 2 이상이라면 value를 대체하는 방식으로 구현.

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        int[] answer = { 0, 0 };
        TreeMap<Integer, Integer> m = new TreeMap<>();

        for(String cur : operations){
            String[] tmp = cur.split(" ");
            if(tmp[0].equals("I")) {
                Integer x = Integer.parseInt(tmp[1]);
                m.put(x, m.getOrDefault(x, 0) + 1);
            } else {
                Map.Entry<Integer, Integer> e = null;

                if(m.isEmpty()) continue;
                if(tmp[1].equals("1")) e = m.lastEntry();
                else e = m.firstEntry();

                if (e.getValue() == 1) m.remove(e.getKey());  
                else m.put(e.getKey(), m.get(e.getKey()) - 1);
            }
        }

        if(!m.isEmpty()) {
            answer[0] = m.lastEntry().getKey();
            answer[1] = m.firstEntry().getKey();
        }

        return answer;
    }
}
728x90

'알고리즘' 카테고리의 다른 글

프로그래머스 - 전력망을 둘로 나누기 (Java, 완전 탐색, bfs)  (0) 2025.03.05
프로그래머스 - 소수 찾기 (Java, 백트래킹, 소수, 에라토스테네스의 체)  (0) 2025.03.04
DP 개념과 문제풀이 방식  (0) 2024.08.20
포인터, alias 개념과 직접 구현 해시  (0) 2024.08.20
외판원 순회(TSP) 알고리즘  (0) 2024.08.20
'알고리즘' 카테고리의 다른 글
  • 프로그래머스 - 전력망을 둘로 나누기 (Java, 완전 탐색, bfs)
  • 프로그래머스 - 소수 찾기 (Java, 백트래킹, 소수, 에라토스테네스의 체)
  • DP 개념과 문제풀이 방식
  • 포인터, alias 개념과 직접 구현 해시
suhsein
suhsein
티끌모아 태산
  • suhsein
    기억 못 할 거면 기록이라는 좋은 수단이 있다
    suhsein
  • 전체
    오늘
    어제
    • 분류 전체보기
      • ASAC
      • Next.js
      • Docker
      • MySQL
      • Java
      • Spring-Proxy, AOP
      • Spring Boot, JPA
      • Spring Security
      • DB
      • 알고리즘
      • PS
      • TOPCIT
      • AWS 자격증
      • 비공개
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • 안녕하세요
  • 인기 글

  • 태그

    tsp
    DP
    티스토리챌린지
    오블완
    Alias
    해시
    포인터
    동적프로그래밍
    외판원순회
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
suhsein
프로그래머스 - 이중우선순위큐 (Java)
상단으로

티스토리툴바