Lv 3. 이중우선순위큐

2024. 9. 18. 17:10·Algorithm & Data Structures/Programers

https://school.programmers.co.kr/learn/courses/30/lessons/42628

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

// 차례대로 반복문 돌린다.
// 들어온 string에 l, D 1 , D -1 의 명령어 분기처리
// 최대 최소 priority queue 0과 끝자리 탐색 해서 return  || 없으면 0,0 반환

// 명령어 분기
// I 삽입
// D 1 최대 삭제
// D -1 최소 삭제
import java.util.*;

class Solution {
    private PriorityQueue<Integer> pq = new PriorityQueue<>();
    public void action(String str){
        if(str.contains("D")){
            if(pq.isEmpty()) return;
            if(str.contains("-1")) //최소삭제
                pq.poll();
            else{ //최대삭제
                int removeElement = pq.stream().max(Integer::compareTo).get();
                pq.remove(removeElement);
            }
        }
        else
            pq.add(Integer.parseInt(
                str.substring(2,
                              str.length())));
        
    }
    public int[] solution(String[] operations) {
        int[] answer = {0,0};
        for(String s : operations)
            action(s);
        if(pq.isEmpty()) return answer;
        answer[0] = pq.stream().max(Integer::compareTo).orElse(null);
        answer[1] = pq.peek();
        System.out.println(answer[0]+" "+answer[1]);
        return answer;
    }
}
// 위코드는 최소는 비교적쉽게 제거하나 최대는 stream()으로 순회하여 확인하고 찾아낸다.

// 아래의 코드는 두개의 우선순위큐를 사용하여 해결한 문제다.
보다 효율적이다.

import java.util.*;

class Solution {
    private PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // 최소 힙
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // 최대 힙

    public void action(String str){
        if(str.startsWith("I")) {
            int number = Integer.parseInt(str.substring(2));
            minHeap.add(number);
            maxHeap.add(number);
        } else if (!minHeap.isEmpty()) {
            if(str.equals("D 1")) {
                // 최대 힙에서 최대 요소 삭제
                int max = maxHeap.poll();
                minHeap.remove(max);
            } else if (str.equals("D -1")) {
                // 최소 힙에서 최소 요소 삭제
                int min = minHeap.poll();
                maxHeap.remove(min);
            }
        }
    }

    public int[] solution(String[] operations) {
        for(String operation : operations) {
            action(operation);
        }
        
        int[] answer = new int[2];
        if (!minHeap.isEmpty()) {
            answer[0] = maxHeap.peek();
            answer[1] = minHeap.peek();
        }
        return answer;
    }
}

'Algorithm & Data Structures > Programers' 카테고리의 다른 글

Lv 3. 네트워크  (0) 2024.09.21
Lv 3. 정수 삼각형  (0) 2024.09.19
Lv 2. 후보키  (2) 2024.09.16
Lv 2. 점찍기  (1) 2024.09.12
Lv 2. 광물 캐기  (0) 2024.09.10
'Algorithm & Data Structures/Programers' 카테고리의 다른 글
  • Lv 3. 네트워크
  • Lv 3. 정수 삼각형
  • Lv 2. 후보키
  • Lv 2. 점찍기
Geisha
Geisha
개발 일기
  • Geisha
    Geisha
    Geisha
  • 전체
    오늘
    어제
    • 분류 전체보기 (343)
      • Algorithm & Data Structures (261)
        • BOJ (119)
        • SWEA (1)
        • Programers (137)
        • Data Structures (3)
      • DB (29)
        • SQL (23)
        • RDBMS (2)
      • Java (1)
        • Class (1)
      • Spring (5)
        • Spring MVC (1)
        • Annotations (1)
      • CS (36)
        • 운영체제 (13)
        • 네트워크 (5)
      • Tool (6)
        • Git (5)
        • AWS (1)
      • Project (1)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    구현
    투포인터
    dp
    Stack
    programmers
    SQL
    다이나믹 프로그래밍
    DynamicProgramming
    골드
    이분탐색
    Dijkstra
    프로그래머스
    백트래킹
    Union-Find
    PriorityQueue
    경로압축
    유니온파인드
    baekjoon
    후위순회
    스택
    dfs
    알고리즘
    binarySearch
    백준
    다익스트라
    자바
    동적계획법
    Java
    algorithm
    BFS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
Geisha
Lv 3. 이중우선순위큐
상단으로

티스토리툴바