1 parent 9c5b0d4 commit 57168b7Copy full SHA for 57168b7
1 file changed
LeetCode/KthLargest.py
@@ -0,0 +1,35 @@
1
+import heapq
2
+
3
4
+class KthLargest(object):
5
6
+ def __init__(self, k, nums):
7
+ """
8
+ :type k: int
9
+ :type nums: List[int]
10
11
+ self.min_heap = []
12
+ self.capacity = k
13
+ self.iterable = nums
14
+ self.get()
15
16
+ def add(self, val):
17
18
+ :type val: int
19
+ :rtype: int
20
21
+ if len(self.min_heap) >= self.capacity:
22
+ if val > self.min_heap[0]:
23
+ heapq.heapreplace(self.min_heap, val)
24
+ else:
25
+ heapq.heappush(self.min_heap, val)
26
27
+ return self.min_heap[0]
28
29
+ def get(self):
30
+ for item in self.iterable:
31
+ self.add(item)
32
33
+# Your KthLargest object will be instantiated and called as such:
34
+# obj = KthLargest(k, nums)
35
+# param_1 = obj.add(val)
0 commit comments