Heap
In Java, PriorityQueue can be used as a Heap.
Task
λ λ§΅κ² in Programmers (Level 2)
π Problem
https://programmers.co.kr/learn/courses/30/lessons/42626
π The point
- Use PriorityQueue & Min-Heap
PriorityQueue<Integer> heap = new PriorityQueue<>();
- to pick the minimum value
When I face problems which need to get the minimum value or the maximum value,
It's more efficient if I use PriorityQueue! Let's apply it afterwards π
π Answer
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
39
40
41
import java.util.PriorityQueue;
class Solution {
public int solution(int[] scoville, int K) {
int answer = 0;
// Used min-heap
PriorityQueue<Integer> heap = new PriorityQueue<>();
// convert int array to PriorityQueue
// ex. scoville [1, 2, 9, 3, 10, 12] -> heap [1, 2, 3, 9, 10, 12]
for (int i = 0; i < scoville.length; i++)
heap.offer(scoville[i]);
while (heap.peek() < K) {
if (heap.size() < 2) return -1; // if all datas can't be K or more
int f1 = heap.poll(); // get the minimum value and remove
int f2 = heap.poll();
int newFood = f1 + (f2 * 2);
heap.offer(newFood); // add data
answer++;
}
return answer;
}
}
/**
[Question]
- scoville : λͺ¨λ μμμ μ€μ½λΉ μ§μ (value : 2 or more and 1,000,000 or less)
- K : μ€μ½λΉ μ§μ (value : 0 or more and 1,000,000 or less)
- return : μμ΄μΌ νλ μ΅μ νμ for λͺ¨λ μμμ μ€μ½λΉ μ§μ >= K
- λ§λ€ μ μλ κ²½μ°μλ -1
- μμ μμμ μ€μ½λΉ μ§μ = κ°μ₯ λ§΅μ§ μμ μμμ μ€μ½λΉ μ§μ
+ (λ λ²μ§Έλ‘ λ§΅μ§ μμ μμμ μ€μ½λΉ μ§μ * 2)
**/
The source : https://velog.io/@peppermint100/Algoνλ‘κ·Έλλ¨Έμ€-λ-맡κ²-in-Java
Comments powered by Disqus.