zoukankan      html  css  js  c++  java
  • 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);
     */
    
  • 相关阅读:
    POJ 1088 滑雪
    POJ 2243 Knight Moves
    poj1847
    poj1995
    poj2230
    poj2007
    poj2376
    socket与TcpListener/TcpClient/UdpClient 的区别及联系
    利用DescriptionAttribute定义枚举值的描述信息
    可以关注的Android网上信息
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946267.html
Copyright © 2011-2022 走看看