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

gonudayo·2021년 8월 19일
0
post-thumbnail

아주 간단하다.

풀이

  1. 우선순위 큐에 스코빌 값을 넣는다.
  2. 가장 낮은 값이 K 이상이 될 때까지 반복한다.
    2-1. 음식을 섞기 위해서는 2개 이상은 존재해야한다.
    2-2. 조건이 만족한다면, 낮은 순서대로 정렬된 두 값을 계산하고 큐에 새로 추가한다.
  3. 섞을 수 없는 경우 -1 리턴

전체코드

import java.util.PriorityQueue;

class Solution {
    public int solution(int[] scoville, int K) {
        PriorityQueue<Integer> prioQ = new PriorityQueue<>();
        int answer = 0;
        
        for(int i = 0; i < scoville.length; i++) {
            prioQ.add(scoville[i]);
        }
        
        while(prioQ.peek() < K) {
            if(prioQ.size() < 2) return -1;
            prioQ.add(prioQ.poll() + (prioQ.poll() * 2));
            answer++;
        }
        
        return answer;
    }
}

우선 순위 큐에 넣기

PriorityQueue<Integer> prioQ = new PriorityQueue<>();

for(int i = 0; i < scoville.length; i++) {
	prioQ.add(scoville[i]);
}
  • 오름차순으로 정렬 된다.
  • 내림차순 정렬은
    PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());

K 이상이 될때까지 섞기

int answer = 0;

while(prioQ.peek() < K) {
	if(prioQ.size() < 2) return -1;
	prioQ.add(prioQ.poll() + (prioQ.poll() * 2));
	answer++;
}

return answer;
  • 설명이 필요없다.
profile
초신성 백엔드 개발자

0개의 댓글