๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋” ๋งต๊ฒŒ

๋ฐ˜์‘ํ˜•

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋” ๋งต๊ฒŒ

https://programmers.co.kr/learn/courses/30/lessons/42626

๋ฌธ์ œ์ ‘๊ทผ

์ฃผ์–ด์ง„ ์Œ์‹ ๋ฐฐ์—ด์—์„œ ์Šค์ฝ”๋นŒ์ง€์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋‚ฎ์€ ๋‘ ์Œ์‹์„ ์„ž์–ด์„œ ๊ธฐ์ค€์ธ K๋ฅผ ๋„˜๊ฒจ์•ผ ํ•œ๋‹ค. ๋‘ ์Œ์‹์„ ์„ž์€ ๊ฒฐ๊ณผ๋„ ๋‹ค์‹œ ์Œ์‹ ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•ด์„œ ์—ฐ์‚ฐ์„ ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๊ณ„์†ํ•ด์„œ ์˜ค๋ฆ„์ฐจ์ˆœ์„ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ์†Œํž™์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

Code

import java.util.PriorityQueue;

class Solution {
    public int solution(int[] scoville, int K) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for(int food: scoville) minHeap.add(food);
        int answer = 0;
        while(minHeap.size() >1 && minHeap.peek()<K){
            int food1 = minHeap.poll();
            int food2 = minHeap.poll();
            minHeap.add(food1 + food2 * 2);
            answer++;
        }
        if(minHeap.isEmpty() || minHeap.peek() < K) return -1;
        else return answer;
    }
}

๋ฐฐ์šด ์  / ์–ด๋ ค์› ๋˜ ์  / ๋Š๋‚€ ์ 

PriorityQueue๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ตœ์†Œ ํž™์„ ๊ฐ„๋‹จํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
์„ ์–ธํ•  ๋•Œ new PriorityQueue<>(Collections.reverseOrder()); ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ตœ๋Œ€ ํž™์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

// ์ตœ์†Œ ํž™
PriorityQueue<Integer> minHeap = new PriorityQueue<>();

// ์ตœ๋Œ€ ํž™
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
๋ฐ˜์‘ํ˜•