처음에 재귀로 풀었는데 효율성 테스트에서 통과를 못했다.
찾아보니까 복잡도를 떠나서 효율 측면에서 반복문보다 떨어진다고 한다.
class Solution {
static class MinHeap {
int[] a;
int count = 0;
public MinHeap(int size) {
a = new int[size];
}
private int parent(int index) {
if (index == 0)
return 0;
return (index - 1) / 2;
}
private int left(int index) {
return 2 * index + 1;
}
private int right(int index) {
return 2 * index + 2;
}
private void swap(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private void heapifyUp(int i) {
if (i == 0)
return;
int parent = parent(i);
if (a[parent] > a[i])
swap(i, parent);
heapifyUp(parent);
}
public void heapifyDown(int i) {
int left = left(i), right = right(i);
int smaller;
if (right < count)
smaller = (a[left] < a[right]) ? left : right;
else if (left < count)
smaller = left;
else
return;
if (a[smaller] < a[i]) {
swap(smaller, i);
heapifyDown(smaller);
}
}
public void buildHeap() {
for (int i = count / 2; i >= 0; --i)
heapifyDown(i);
}
public void add(int value) {
int index = count++;
a[index] = value;
heapifyUp(index);
}
public int removeTop() {
if (count <= 0)
return Integer.MIN_VALUE;
int r = a[0];
a[0] = a[--count];
heapifyDown(0);
return r;
}
public int getValue(int index)
{
return a[index];
}
}
public static int Scoville(MinHeap heap,int K, int count) {
while(true)
{
if(heap.getValue(0)>=K)
return count;
if(heap.count==1)
return -1;
int num = (heap.removeTop()+(heap.removeTop()*2));
heap.add(num);
count+=1;
}
}
public int solution(int[] scoville, int K) {
MinHeap heap = new MinHeap(scoville.length);
for (int i = 0; i < scoville.length; ++i) {
heap.add(scoville[i]);
}
int answer= Scoville(heap,K,0);
return answer;
}
}