703. Kth Largest Element in a Stream实时求第K个最大的元素

设计一个类来查找流中的第K个最大元素。这不是第K个不同的元素,而是排序后的第K个最大元素。可以使用小顶堆(min heap)来实现,当有新元素时,与堆顶比较,如果新元素更大则替换堆顶,保持堆的大小为K,从而实时返回第K大的元素。
摘要由CSDN通过智能技术生成

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.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

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


思路1
保存前k个最大的值——》sorted
用快排排序,复杂度也至少Nklogk

思路2
使用min heap 小顶堆, size = k
每次拿新的数和堆顶比较,如果新元素大,则删除堆顶把新元素加进来。
复杂度:NlogK(堆的维护时间)

#include <iostream>
#include <queue>
class KthLargest {
private:
    std::priority_queue<int, std::vector<int>, std::greater<int> >  pq; // 小顶堆
    int size;
public:
    KthLargest(int k, std::vector<int>& nums) {
        size = k;
        for(auto number : nums) {
            add(number);
        }
    }
    
    int add(int val) {
        if (size > pq.size()) {
            pq.push(val);
            return pq.top();
        }
        if (val > pq.top()) {
            pq.pop();
            pq.push(val);
        }
        return pq.top();
    }
};
#include <iostream>
#include "KthLargest.cpp"
#include <vector>

int main() {
    std::vector<int> nums = { 4, 5, 8, 2};
    KthLargest *kthlargest = new KthLargest(3, nums);
    int newNum;
    while (std::cin >> newNum) {
        std::cout << kthlargest->add(newNum);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值