Home [Algorithm] Heap
Post
Cancel

[Algorithm] Heap

Heap

In Java, PriorityQueue can be used as a Heap.

Detail


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

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Hash2

[Data Sturcture] Heap

Comments powered by Disqus.