设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
1 2 3 4 5 6 7 8
| int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); kthLargest.add(5); kthLargest.add(10); kthLargest.add(9); kthLargest.add(4);
|
说明:
- 你可以假设 nums 的长度≥ k-1 且k ≥ 1。
解答:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class KthLargest { private int k; private PriorityQueue<Integer> q;
public KthLargest(int k, int[] nums) { this.k = k; this.q = new PriorityQueue<>(k); for (int num : nums) { this.add(num); } }
public int add(int val) { if (this.q.size() < k) this.q.offer(val); else if (this.q.peek() < val) { this.q.poll(); this.q.offer(val); } return this.q.peek(); } }
|
主要的坑