Skip to content

Commit 66fe3d6

Browse files
authored
Create Kth Largest Element in a Stream.py
1 parent de403d3 commit 66fe3d6

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Kth Largest Element in a Stream.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
3+
4+
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
5+
6+
Example:
7+
8+
int k = 3;
9+
int[] arr = [4,5,8,2];
10+
KthLargest kthLargest = new KthLargest(3, arr);
11+
kthLargest.add(3); // returns 4
12+
kthLargest.add(5); // returns 5
13+
kthLargest.add(10); // returns 5
14+
kthLargest.add(9); // returns 8
15+
kthLargest.add(4); // returns 8
16+
Note:
17+
You may assume that nums' length ≥ k-1 and k ≥ 1.
18+
'''
19+
20+
import heapq
21+
22+
class KthLargest(object):
23+
24+
def __init__(self, k, nums):
25+
"""
26+
:type k: int
27+
:type nums: List[int]
28+
"""
29+
self.h = []
30+
self.k = k
31+
for num in nums:
32+
heapq.heappush(self.h, num)
33+
if len(self.h) > self.k:
34+
heapq.heappop(self.h)
35+
36+
def add(self, val):
37+
"""
38+
:type val: int
39+
:rtype: int
40+
"""
41+
heapq.heappush(self.h, val)
42+
if len(self.h) > self.k:
43+
heapq.heappop(self.h)
44+
return self.h[0]
45+
46+
47+
# Your KthLargest object will be instantiated and called as such:
48+
# obj = KthLargest(k, nums)
49+
# param_1 = obj.add(val)

0 commit comments

Comments
 (0)