-
Notifications
You must be signed in to change notification settings - Fork 0
/
KthLargestElementInAStream.py
40 lines (33 loc) · 1.27 KB
/
KthLargestElementInAStream.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.min_heap = []
for num in nums:
self.add(num)
def add(self, val: int) -> int:
if len(self.min_heap) < self.k or self.min_heap[0] < val:
heapq.heappush(self.min_heap, val)
if len(self.min_heap) > self.k:
heapq.heappop(self.min_heap)
return self.min_heap[0]
# initial solution: created a heap with all elements. unnecessary, and resulted in time limit exceeded
# def __init__(self, k: int, nums: List[int]):
# self.k = k
# self.max_heap = [-n for n in nums]
# heapq.heapify(self.max_heap)
# def add(self, val: int) -> int:
# heappush(self.max_heap, -val)
# popped = []
# for _ in range(self.k):
# if not self.max_heap:
# for el in popped:
# heapq.heappush(self.max_heap, el)
# return None
# popped.append(heapq.heappop(self.max_heap))
# res = -popped[-1]
# while popped:
# heapq.heappush(self.max_heap, popped.pop())
# return res
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)