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);
     */
    
  • 相关阅读:
    JVM(二)JVM内存布局
    JVM(一) OpenJDK1.8源码在Ubuntu16.04下的编译
    阿里面试
    npm run dev/npm run start报错
    vue 项目报错 You may use special comments to disable some warnings.
    ES6模块化
    jQuery中的动画
    jsonp的封装
    ajax中get,post,以及二合一的封装
    小案例之刮奖
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074779.html
Copyright © 2011-2022 走看看