class KthLargest: #Big O: n def __init__(self, k: int, nums: List[int]): #minHeap with k largest integers self.minHeap, self.k = nums, k heapq.heapify(self.minHeap) while len(self.minHeap) > k: heapq.heappop(self.minHeap) #Big O: log N def add(self, val: int) -> int: heapq.heappush(self.minHeap, val) if len(self.minHeap) > self.k: heapq.heappop(self.minHeap) return self.minHeap[0] #Total big O: n log n # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter