题目:超过阈值的最少操作数 II
思路
一眼想到用小根堆,学到了一些小根堆的相关的信息
收获
- heap.add(),添加元素
- heap.poll(),获取堆顶元素,并移除
- heap.peek(),获取堆顶元素
- heap.size(),获取堆的元素数量
代码
class Solution {public int minOperations(int[] nums, int k) {int res = 0;PriorityQueue<Integer> heap = new PriorityQueue<>();for (int num : nums) {if (num < k) heap.add(num);}while (heap.size() > 0) {res++;System.out.println(heap.size());if (heap.size() == 1) break;int m1 = heap.poll();int m2 = heap.poll();long t = (long)m1 * 2 + m2;if (t < k) {int s = (int) t;System.out.println(s);heap.add(s);}}return res;}
}