kth-largest-element-in-a-streamV1.py (589B)
1 from heapq import heappush, heappop, nlargest 2 3 4 class KthLargest: 5 6 def __init__(self, k: int, nums: List[int]): 7 self.ls = nums 8 self.ls.sort() 9 10 while len(self.ls) > k: 11 self.ls = self.ls[1:] 12 13 self.k = k 14 15 def add(self, val: int) -> int: 16 self.ls.append(val) 17 self.ls.sort() 18 ret_val = self.ls[-self.k] 19 20 while len(self.ls) > self.k: 21 self.ls = self.ls[1:] 22 23 return ret_val 24 25 26 # Your KthLargest object will be instantiated and called as such: 27 # obj = KthLargest(k, nums) 28 # param_1 = obj.add(val)