[LeetCode] 703. Kth Largest Element in a Stream
Design a class to find the kth
largest element in a stream. Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
Implement KthLargest
class:
KthLargest(int k, int[] nums)
Initializes the object with the integerk
and the stream of integersnums
.int add(int val)
Returns the element representing thekth
largest element in the stream.
Example 1:
Input ["KthLargest", "add", "add", "add", "add", "add"] [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] Output [null, 4, 5, 5, 8, 8] Explanation KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8
Constraints:
1 <= k <= 104
0 <= nums.length <= 104
-104 <= nums[i] <= 104
-104 <= val <= 104
- At most
104
calls will be made toadd
. - It is guaranteed that there will be at least
k
elements in the array when you search for thekth
element.
数据流中第K大的元素。
设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。
请实现 KthLargest 类:
KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
int add(int val) 将 val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-a-stream
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题干即是题意,请设计一个class,找到数据流中第K大的元素。
思路是用Java中的PriorityQueue去实现一个最小堆(min heap),同时控制堆的size为K。首先先把nums数组中的元素全都放进pq,当pq的size大于K的时候,无论nums中的元素是否放完,我们都无条件弹出堆顶元素,一直保持pq中元素的个数是K。这样当我们再peek堆顶的时候,堆顶元素即是所求的第K大的元素。
时间 初始化,O(n * logk),n是一开始 nums 的长度;单次插入的时间复杂度是O(log k)
空间 O(k) - pq的大小
1 class KthLargest { 2 int kk; 3 PriorityQueue<Integer> queue; 4 5 public KthLargest(int k, int[] nums) { 6 this.kk = k; 7 queue = new PriorityQueue<>(); 8 for (int num : nums) { 9 add(num); 10 } 11 } 12 13 public int add(int val) { 14 queue.offer(val); 15 // 弹出的是最小的元素,所以最后会保留K个最大的元素 16 if (queue.size() > kk) { 17 queue.poll(); 18 } 19 return queue.peek(); 20 } 21 } 22 23 /** 24 * Your KthLargest object will be instantiated and called as such: 25 * KthLargest obj = new KthLargest(k, nums); 26 * int param_1 = obj.add(val); 27 */