程序媛詹妮弗
终身学习

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 integer k and the stream of integers nums.
  • int add(int val) Returns the element representing the kth 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 to add.
  • It is guaranteed that there will be at least k elements in the array when you search for the kth element.

题意

设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。


 

思路

  1. 先试着对给定的an integer k and an integer array nums进行一下构造函数constructoer的设计使得其包含数据流最初这些给定参数
  2. 每次从数据流新加入的data ,就跟堆顶元素比较一下:比堆顶元素小,直接忽略;比堆顶元素大,就堆顶元素让位。而该堆mantain了k size个最大元素,所以每次返回的堆顶元素,就是第K 大元素

 

代码

/*
Time:O(n * logk) 假设数据个数为n对每个数据,最坏情况下,每次都打掉堆顶元素,priorityqueue内部又得重新排序,ksize的priorityqueue的排序时间为logk, 所以总时间是 n 乘以 logk
Space: O(k) 额外开了 k size的priorityqueue做辅助
*/
class KthLargest {
    PriorityQueue<Integer> minHeap;
    int k;
    
    //constructor
    public KthLargest (int k, int[] nums) {
        this.k = k;
        minHeap = new PriorityQueue<>(k); // Java PriorityQueue is a min heap in default
        for(int n : nums){
            add(n);
        }
    }

    public int add(int val) {
        if(minHeap.size() < k){
            minHeap.offer(val);
        }else if(minHeap.peek() < val){
            minHeap.poll();
            minHeap.offer(val);
        }
        return minHeap.peek();
    }
}

  

posted on 2020-12-29 02:58  程序媛詹妮弗  阅读(150)  评论(0编辑  收藏  举报