프로그래머스 - 힙 - 이중우선순위큐
2021. 3. 23. 10:40ㆍAlgorithm
programmers.co.kr/learn/courses/30/lessons/42628
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
32
33
34
35
36
37
38
|
package dataStructure.heap;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;
public class 이중우선순위큐 {
public static void main(String[] args) {
이중우선순위큐 o = new 이중우선순위큐();
System.out.println(Arrays.toString(o.solution(new String[]{"I 16","D 1"})));
}
public int[] solution(String[] operations) {
Queue<Integer> maxQ = new PriorityQueue<>(Collections.reverseOrder());
Queue<Integer> minQ = new PriorityQueue<>();
for(int i=0; i<operations.length; i++) {
String[] operation = operations[i].split(" ");
String operator = operation[0];
Integer number = Integer.valueOf(operation[1]);
if(operator.equals("I")) {
maxQ.offer(number);
minQ.offer(number);
} else {
if(number == 1) {
minQ.remove(maxQ.poll());
} else {
maxQ.remove(minQ.poll());
}
}
}
return new int[]{maxQ.peek() == null ? 0 : maxQ.peek(), minQ.peek() == null ? 0 : minQ.peek()};
}
}
|
cs |
알고리즘
- 힙
- 우선순위큐를 활용하여 최대값과 최소값을 구할 수 있는지에 대한 문제이다.
- 간단하게 최대값 우선순위큐와 최소값 우선순위큐 두 개를 만들어 활용하면된다.
- 단, 삽입 및 삭제시 두 큐에 동일하게 삽입, 삭제 되어야 한다.
'Algorithm' 카테고리의 다른 글
백준 - 1759 - 암호 만들기 (0) | 2021.03.23 |
---|---|
백준 - 6603 - 로또 (0) | 2021.03.23 |
프로그래머스 - 힙 - 디스크 컨트롤러 (0) | 2021.03.22 |
프로그래머스 - 힙 - 더 맵게 (0) | 2021.03.21 |
프로그래머스 - 큐 - 기능개발 (0) | 2021.03.18 |