Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 리액트 성능 최적화
- DFS
- Greedy
- Kruskal Algorithm
- Modern Javascript
- heap
- useReducer
- JS Array Functions
- 리액트 상태값 업데이트
- java
- Segment Tree
- 프로그래머스#JAVA
- 객체지향 설계 5원칙
- batch udpate
- spread operator
- rest operator
- 리액트의 작동방식
- react
- useContext
- codility
- React 훅 사용규칙
- State
- BOJ2042
- 섬 연결하기
- 프로그래머스
- useState
- DB Navigator
- Lifting State Up
- state update scheduling
- MST구현
Archives
- Today
- Total
개발하는SM
[프로그래머스] 이중우선순위큐 본문
programmers.co.kr/learn/courses/30/lessons/42628
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어수신 탑(높이)
I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
D 1 | 큐에서 최댓값을 삭제합니다. |
D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
풀이
maxHeap 이나 minHeap 을 가지고 어떻게 이중 우선순위큐를 만들지 고민했는데..
PriorityQueue 클래스에 remove(int val) 메소드가 있었다.....
해당 메소드를 사용하여 무난하게 풀 수 있었던 문제였음
다음부턴 꼭 기억하고 쓸 수 있도록 할것
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> (a-b) * -1);
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for(String s : operations){
if(s.charAt(0) == 'I'){
int num = Integer.parseInt(s.substring(2));
maxHeap.offer(num);
minHeap.offer(num);
}else{
if(s.charAt(2) == '-'){
if(minHeap.isEmpty()) continue;
int min = minHeap.poll();
maxHeap.remove(min);
}else{
if(maxHeap.isEmpty()) continue;
int max = maxHeap.poll();
minHeap.remove(max);
}
}
}
if(minHeap.isEmpty()) return new int[] {0,0};
return new int[] {maxHeap.poll(), minHeap.poll()};
}
}
'Algorithm > Heap' 카테고리의 다른 글
Heap 과 우선순위 큐(Priority Queue) (0) | 2021.02.12 |
---|---|
[프로그래머스] 디스크 컨트롤러 (0) | 2021.02.12 |
[프로그래머스] 더 맵게 (0) | 2021.02.12 |