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

괜찮아요?·2023년 4월 4일
0

programmers

목록 보기
16/23


링크

코딩테스트 연습 > 힙(heap) > 더 맵게

풀이순서

  1. PriorityQueue에 값 삽입.
  2. 작은 수 두개 꺼내서 수식계산

코드

import java.util.*;

class Solution {
    public int solution(int[] scoville, int K) {
        int answer = 0;
        PriorityQueue<Integer> q = new PriorityQueue();
        
        for(int sco: scoville){
            q.add(sco);
        }
        
        while(q.peek() < K){
            int lessSpicy = q.poll();
            
            if(!q.isEmpty()){
                int secondLessSpicy = q.poll();
                q.add(lessSpicy+secondLessSpicy*2);
                answer++;
            }else{return -1;}
        }
        return answer;
    }
}

참고

  • heap(힙) : 최솟값 또는 최댓값을 빠르게 찾아내기 위해 완전이진트리 형태로 만들어진 자료구조
  • //낮은 숫자가 우선 순위인 int 형 우선순위 큐 선언
    PriorityQueue priorityQueueLowest = new PriorityQueue<>();
  • //높은 숫자가 우선 순위인 int 형 우선순위 큐 선언
    PriorityQueue priorityQueueHighest = new PriorityQueue<>(Collections.reverseOrder());
profile
할 수 있어요

0개의 댓글