알고리즘 풀이/프로그래머스

[프로그래머스][Java] 더 맵게

배게 2019. 3. 22. 02:12
728x90

우선순위 큐에 대한 개념이 필요한 문제


Integer에 대해서 오름차순으로 자동정렬되는 것만 알면 쉬움


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.*;

class Solution {
    public int solution(int[] scoville, int K) {
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        int answer = 0;

        for(int i: scoville) pq.add(i);

        while(true){
            if(pq.peek()>=K) break;
            if(pq.size()==1) return -1;
            else {
                pq.add(pq.poll() + (pq.poll())*2);
                answer++;
            }
        }

        return answer;
    }
}


참고 : https://developerdk.tistory.com/20

댓글수0