- 문제 : 프로그래머스 더 맵게
문제내용
풀이
모든 원소의 스코빌 지수를 주어진 수 K 이상으로 만들어야하며 스코빌 지수가 가장 낮은 두개의 음식을 섞어서 하나로 만들기 때문에 정렬하여 섞어주려고 우선순위 큐(Priority Queue)를 구현하여 두개를 뽑아 다시 넣는 방식으로 구현하였고 poll 했을 때 가장 낮은 숫자가 나오는 정렬된 자료구조이기 때문에 poll 시 K보다 같거나 크다면 종료하여 횟수를 리턴하였다.
우선순위 큐
PriorityQueue<Integer> pq = new PriorityQueue<>();
전체코드
import java.util.*;
class Solution {
public int solution(int[] scoville, int K) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int element : scoville){
pq.add(element);
}
int time = 0;
while(true){
if(pq.peek() >= K) break;
else{
if(pq.size() < 2) return -1;
int e1 = pq.poll();
int e2 = pq.poll();
int mix = e1 + e2 * 2;
pq.add(mix);
time++;
}
}
return time;
}
}
결과
'알고리즘 문제풀이' 카테고리의 다른 글
프로그래머스 광고 삽입 (JAVA) (0) | 2021.08.23 |
---|---|
프로그래머스 H-Index (JAVA) (0) | 2021.08.21 |
[복기] Java - 국민은행 210703 (0) | 2021.07.06 |