Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 48d0930

Browse files
authored
Add files via upload
1 parent 9c6e2f1 commit 48d0930

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎Top_K_Elements/k_largest.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import heapq
2+
3+
class KthLargest:
4+
# Constructor to initialize heap and add values in it
5+
def __init__(self, k, nums):
6+
7+
self.top_k_heap = []
8+
self.k = k
9+
10+
for element in nums:
11+
self.add(element)
12+
13+
14+
15+
# Adds element in the heap and return the Kth largest
16+
def add(self, val):
17+
18+
if len(self.top_k_heap) < self.k:
19+
heapq.heappush(self.top_k_heap, val)
20+
21+
elif val > self.top_k_heap[0]:
22+
heapq.heappop(self.top_k_heap)
23+
heapq.heappush(self.top_k_heap, val)
24+
25+
return self.top_k_heap[0]
26+
27+
28+
# Time Complexity = O(logk)
29+
# Space Complexity = O(K)
30+
31+
32+
33+
############################################################################
34+
35+
36+
37+
# Driver code
38+
def main():
39+
nums = [3, 6, 9, 10]
40+
temp = [3, 6, 9, 10]
41+
print("Initial stream: ", nums, sep = "")
42+
print("k: ", 3, sep = "")
43+
k_largest = KthLargest(3, nums)
44+
val = [4, 7, 10, 8, 15]
45+
for i in range(len(val)):
46+
print("\tAdding a new number ", val[i], " to the stream", sep = "")
47+
temp.append(val[i])
48+
print("\tNumber stream: ", temp, sep = "")
49+
print("\tKth largest element in the stream: ", k_largest.add(val[i]))
50+
print("-"*100)
51+
52+
if __name__ == "__main__":
53+
main()
54+
55+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /