문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/42626
단순하게 배열이나 리스트를 사용하여 소팅하면 시간 초과가 나는 문제였다.
우선순위 큐를 사용하여 풀었다.
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.util.Collections; import java.util.PriorityQueue; class Solution { public int solution(int[] scoville, int K) { int answer = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int i=0; i<scoville.length; i++) { pq.add(scoville[i]); } while(true) { if(pq.peek()>=K) break; if(pq.size()==1) { answer = -1; break; } int t1 = pq.poll(); int t2 = pq.poll(); int t3 = t1 + (t2*2); pq.add(t3); answer++; } return answer; } } | cs |