美文网首页
5.Kth Largest Element in a Strea

5.Kth Largest Element in a Strea

作者: 0Xday | 来源:发表于2018-08-07 21:58 被阅读0次

    PriorityQueue:优先级队列,实际上就是自带排序的队列,操作的方式,对于Bean来说,可以实现Comparable进行排序。
    注意:其是非线程安全的!


    class KthLargest  {
    
        private int k;
        //优先级队列
        private PriorityQueue<Integer> queue;
    
        public KthLargest(int k, int[] nums) {
            this.k  = k;
            queue = new PriorityQueue<>();
            if(nums.length <= k) {
                for(int num:nums) {
                    queue.add(num);  
                }
            }else {
                for(int i = 0;i<k;i++) {
                    queue.add(nums[i]);
                  }  
                for(int i = k;i<nums.length;i++) {
                    //由优先级队列的定义可知,前面k个元素均是从小到大
                    //故插入的元素只需要跟队列最后一个元素比较即可
                    if(queue.peek()<nums[i]) {
                        queue.poll();
                        queue.add(nums[i]);
                    }
                }
            }
        }
    
        public int add(int val) {
            if(queue.size()<k) {
                queue.offer(val);
            }else if(queue.peek()<val) {
                queue.poll();
                queue.offer(val);
            }
            return queue.peek();
        }
    }

    相关文章

      网友评论

          本文标题:5.Kth Largest Element in a Strea

          本文链接:https://www.haomeiwen.com/subject/iddzvftx.html