剑指 Offer II 059. 数据流的第 K 大数值(703. 数据流中的第 K 大元素)
题目:
思路:
【1】用优先队列实现堆的形式
代码展示:
//时间15 ms击败19.10% //内存45.6 MB击败46.16% public class KthLargest { PriorityQueue<Integer> pq; int k; public KthLargest(int k, int[] nums) { this.k = k; pq = new PriorityQueue<Integer>(); for (int x : nums) { add(x); } } //因为只需要保留第K大的元素,所以当初始化[4, 5, 8, 2]时, //前三个因为有限队列缘故(默认升序),故会成为[4, 5, 8] //当塞入2时,变为[2,,4, 5, 8],然后因为超过容量2又会被弹出,变为[4, 5, 8] //此时peek拿到的依旧是4 public int add(int val) { pq.offer(val); while (pq.size() > k) { pq.poll(); } return pq.peek(); } } /** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */