Leetcode 703: Kth Largest Element in a Stream

问题描述:

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.

问题分析:
constructor里面有 public KthLargest(int k, int[] nums) {}, 不代表你的类里面的member variable一定是它们两个。member variable 里面可以有 k, 但数组不一定有。这道题把priority queue设为member variable,在constructor里面用循环语句把array里面的值加入到priority queue,以达到初始化的目的。
为了节省空间,这道题目用了和leetcode219题相似的做法。
(219题要求找数组中一定区间k以内的相同元素。当初我用的hashmap实现的。为了节省空间,我们可以用hashset实现,并且始终把set的容量设置为k,因为太久远的数字对运行结果没有影响。)
同理,这道题可以只保留优先队列最大的k个元素,如果pq中元素个数大于k,我们删去queue头的(最小的)元素,不影响运行结果。

代码如下:

class KthLargest {

    private int kthLargest;
    private PriorityQueue<Integer> pq;
    
    public KthLargest(int k, int[] nums) {
        kthLargest = k;
        pq = new PriorityQueue<Integer>();
        for (int i=0; i<nums.length; i++){
            pq.add(nums[i]);
            if (pq.size()>k){
                pq.poll();
            }
        }
    }
    
    public int add(int val) {
        pq.add(val);
        if (pq.size()>kthLargest){
            pq.poll();
        }
         return pq.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

时间复杂度:O(nlogn)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值