• Java实现 LeetCode 703 数据流中的第K大元素(先序队列)


    703. 数据流中的第K大元素

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

    你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。

    示例:

    int k = 3;
    int[] arr = [4,5,8,2];
    KthLargest kthLargest = new KthLargest(3, arr);
    kthLargest.add(3);   // returns 4
    kthLargest.add(5);   // returns 5
    kthLargest.add(10);  // returns 5
    kthLargest.add(9);   // returns 8
    kthLargest.add(4);   // returns 8
    

    说明:
    你可以假设 nums 的长度≥ k-1 且k ≥ 1。

    class KthLargest {
    
      private PriorityQueue<Integer> queue;
        
        private int kth;
        
        public KthLargest(int k, int[] nums) {
            kth = k;
            queue = new PriorityQueue<>(k);
            for(int x : nums)
                add(x);
        }
        
        public int add(int val) {
            if(queue.size() < kth) {
                queue.add(val);
                return queue.peek();
            }
            if(queue.peek() < val) {
                queue.remove();
                queue.add(val);
            }
            return queue.peek();
        }
    }
    
    /**
     * Your KthLargest object will be instantiated and called as such:
     * KthLargest obj = new KthLargest(k, nums);
     * int param_1 = obj.add(val);
     */
    
  • 相关阅读:
    c/c++ const
    Lucene2.9.1使用小结(同样适用于Lucene 3.0 )
    java 对properties 文件的写操作
    oracle 建表序列插入值
    jxl 读取2003 excel 示例
    HttpClient 的使用
    小故事
    iText 导出word 经典实现
    使用dom4j 解析xml
    lucene 在项目中的使用
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074779.html
Copyright © 2020-2023  润新知