-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkth-largest-element-in-a-stream.py
52 lines (40 loc) · 1.44 KB
/
kth-largest-element-in-a-stream.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
41
42
43
44
45
46
47
48
49
50
51
52
# https://leetcode.com/problems/kth-largest-element-in-a-stream/
from typing import List
from heapq import heapify, heappush, heappushpop
# Runtime: 163 ms, faster than 41.37% of Python3 online submissions for Kth Largest Element in a Stream.
# Memory Usage: 18.2 MB, less than 62.66 % of Python3 online submissions for Kth Largest Element in a Stream.
class KthLargest:
def __init__(self, k: int, nums: List[int]):
# Store the k value
self.k = k
# Sorting and trimming the list is quicker than popping from the heap
# while it is bigger than k
if len(nums) > k:
nums.sort(reverse=True)
nums = nums[:k]
heapify(nums)
self.heap = nums
def add(self, val: int) -> int:
if len(self.heap) < self.k:
heappush(self.heap, val)
elif val > self.heap[0]:
heappushpop(self.heap, val)
return self.heap[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
def test():
sol = KthLargest(3, [4, 5, 8, 2])
assert sol.add(3) == 4
assert sol.add(5) == 5
assert sol.add(10) == 5
assert sol.add(9) == 8
assert sol.add(4) == 8
sol = KthLargest(1, [])
assert sol.add(-3) == -3
assert sol.add(-2) == -2
assert sol.add(-4) == -2
assert sol.add(0) == 0
assert sol.add(4) == 4
# [[1,[]],[-3],[-2],[-4],[0],[4]]
test()