Java
import java.util.PriorityQueue;
import java.util.Queue;
/**
* <a href="https://leetcode.cn/problems/minimum-operations-to-exceed-threshold-ii/">Minimum Operations To Exceed Threshold II</a>
* 数组;模拟;堆(优先队列)
*/
class Solution {
public int minOperations(int[] nums, int k) {
Queue<Long> queue = new PriorityQueue<>();
for (long num : nums) {
queue.add(num);
}
int cnt = 0;
while (queue.size() > 1 && queue.peek() < k) {
long min1 = queue.remove();
long min2 = queue.remove();
queue.add(min1 * 2 + min2);
cnt++;
}
return cnt;
}
}
Go
import "container/heap"
func minOperations(nums []int, k int) int {
res := 0
pq := &MinHeap{}
heap.Init(pq)
for _, num := range nums {
heap.Push(pq, num)
}
for (*pq)[0] < k {
x := heap.Pop(pq).(int)
y := heap.Pop(pq).(int)
heap.Push(pq, x+x+y)
res++
}
return res
}
type MinHeap []int
func (h *MinHeap) Len() int {
return len(*h)
}
func (h *MinHeap) Less(i, j int) bool {
return (*h)[i] < (*h)[j]
}
func (h *MinHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}