zoukankan      html  css  js  c++  java
  • [Leetcode]703. Kth Largest Element in a Stream 数据流中的第 K 大元素

    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();
        }
    }
    

      

  • 相关阅读:
    用批处理实现映射盘网络盘为固定盘符,请更改冲突的硬盘盘符
    linux下mysql寻找my.cnf顺序
    php写memcached ,c读取乱码问题[转]
    linux下boost安装方法
    解决php soap webservice 用c++ soap调用的问题[转]
    【转载】Servlet生命周期与工作原理
    【转载】深入理解Java多态性
    JSP中几个常用的参数与中文乱码问题
    获取数据库连接
    dom4j简单实例
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/14204554.html
Copyright © 2011-2022 走看看