-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthLargest.py
More file actions
35 lines (28 loc) · 779 Bytes
/
KthLargest.py
File metadata and controls
35 lines (28 loc) · 779 Bytes
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
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.min_heap = []
self.capacity = k
self.iterable = nums
self.get()
def add(self, val):
"""
:type val: int
:rtype: int
"""
if len(self.min_heap) >= self.capacity:
if val > self.min_heap[0]:
heapq.heapreplace(self.min_heap, val)
else:
heapq.heappush(self.min_heap, val)
return self.min_heap[0]
def get(self):
for item in self.iterable:
self.add(item)
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)