列表

详情


剑指 Offer II 059. 数据流的第 K 大数值

设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。

请实现 KthLargest 类:

 

示例:

输入:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
输出:
[null, 4, 5, 5, 8, 8]

解释:
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8

 

提示:

 

注意:本题与主站 703 题相同: https://leetcode.cn/problems/kth-largest-element-in-a-stream/

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class KthLargest { public: KthLargest(int k, vector<int>& nums) { } int add(int val) { } }; /** * Your KthLargest object will be instantiated and called as such: * KthLargest* obj = new KthLargest(k, nums); * int param_1 = obj->add(val); */

python3 解法, 执行用时: 84 ms, 内存消耗: 18.7 MB, 提交时间: 2022-05-26 10:57:00

class KthLargest:
    def __init__(self, k: int, nums: List[int]):
        self.HEAP = []
        self.size = k
        for num in nums:
            self._push(num)

    def _push(self, num):
        if len(self.HEAP) < self.size:
                heapq.heappush(self.HEAP, num)
        else:
            if self.HEAP[0] < num:
                heapq.heappop(self.HEAP)
                heapq.heappush(self.HEAP, num)

    def add(self, val: int) -> int:
        self._push(val)
        return self.HEAP[0]
        



# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

上一题