Kth Largest Element In A Stream
If you want k largest or kth largest, implement minheap
Problem Link: https://leetcode.com/problems/kth-largest-element-in-a-stream/
import heapq
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.minheap=nums
self.k=k
heapq.heapify(self.minheap)
while(len(self.minheap)>self.k):
heapq.heappop(self.minheap)
def add(self, val: int) -> int:
heapq.heappush(self.minheap, val)
while(len(self.minheap)>self.k):
heapq.heappop(self.minheap)
return self.minheap[0]
Last updated