kth_largest_element_in_a_stream

 1from heapq import heapify, heappop, heappush
 2
 3
 4# @leet start
 5class KthLargest:
 6    """
 7    This class implements returning the kth largest item in a stream.
 8    To do so, it uses a heap, and only maintains the top k elements.
 9    The heap keeps the k largest elements.
10    When the length of the heap is greater than k, it pops the minimum item.
11    Since python's heap is a min-heap by default, the first item is always the kth
12    item.
13    """
14
15    def __init__(self, k: int, nums: list[int]):
16        self.k = k
17        heapify(self.nums)
18        self.heap = nums
19
20        while len(self.heap) > k:
21            heappop(self.heap)
22
23    def add(self, val: int) -> int:
24        heappush(self.heap, val)
25        if len(self.heap) > self.k:
26            heappop(self.heap)
27        return self.heap[0]
28
29
30# Your KthLargest object will be instantiated and called as such:
31# obj = KthLargest(k, nums)
32# param_1 = obj.add(val)
33# @leet end
34
35
36def test():
37    assert 2 + 2 == 4
class KthLargest:
 6class KthLargest:
 7    """
 8    This class implements returning the kth largest item in a stream.
 9    To do so, it uses a heap, and only maintains the top k elements.
10    The heap keeps the k largest elements.
11    When the length of the heap is greater than k, it pops the minimum item.
12    Since python's heap is a min-heap by default, the first item is always the kth
13    item.
14    """
15
16    def __init__(self, k: int, nums: list[int]):
17        self.k = k
18        heapify(self.nums)
19        self.heap = nums
20
21        while len(self.heap) > k:
22            heappop(self.heap)
23
24    def add(self, val: int) -> int:
25        heappush(self.heap, val)
26        if len(self.heap) > self.k:
27            heappop(self.heap)
28        return self.heap[0]

This class implements returning the kth largest item in a stream. To do so, it uses a heap, and only maintains the top k elements. The heap keeps the k largest elements. When the length of the heap is greater than k, it pops the minimum item. Since python's heap is a min-heap by default, the first item is always the kth item.

KthLargest(k: int, nums: list[int])
16    def __init__(self, k: int, nums: list[int]):
17        self.k = k
18        heapify(self.nums)
19        self.heap = nums
20
21        while len(self.heap) > k:
22            heappop(self.heap)
k
heap
def add(self, val: int) -> int:
24    def add(self, val: int) -> int:
25        heappush(self.heap, val)
26        if len(self.heap) > self.k:
27            heappop(self.heap)
28        return self.heap[0]
def test():
37def test():
38    assert 2 + 2 == 4