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 67eeeb1

Browse files
authored
Add files via upload
1 parent ecc670f commit 67eeeb1

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

‎Top_K_Elements/find_kth_largest.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import heapq
2+
3+
def find_kth_largest(nums, k):
4+
5+
# Initialize an empty list
6+
k_numbers_min_heap = []
7+
8+
# Add first k elements to the list
9+
for i in range(k):
10+
k_numbers_min_heap.append(nums[i])
11+
12+
# Convert list to min_heap
13+
heapq.heapify(k_numbers_min_heap)
14+
15+
# Iterate through remaining elements in num array
16+
for i in range(k, len(nums)):
17+
18+
# Compare current element with min heap element
19+
if nums[i] > k_numbers_min_heap[0]:
20+
21+
# Remove smallest element
22+
heapq.heappop(k_numbers_min_heap)
23+
24+
# Add current element
25+
heapq.heappush(k_numbers_min_heap, nums[i])
26+
27+
return k_numbers_min_heap[0]
28+
29+
30+
31+
# Time Complexity = O((n-k)logk)
32+
# Space Complexity = O(k)
33+
34+
35+
36+
############################################################################
37+
38+
39+
40+
# Driver code
41+
def main():
42+
input_array = [
43+
[1, 5, 12, 2, 11, 9, 7, 30, 20],
44+
[5, 2, 9, -3, 7],
45+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
46+
[1, 4, 6, 0, 2],
47+
[3, 5, 2, 3, 8, 5, 3]
48+
]
49+
50+
k = [3, 1, 9, 1, 4]
51+
52+
for i in range(len(input_array)):
53+
print(i + 1, ".\tInput array: ", input_array[i], sep="")
54+
print("\tValue of k: ", k[i], sep="")
55+
print("\tkth largest number: ", find_kth_largest(input_array[i], k[i]), sep="")
56+
print("-" * 100)
57+
58+
59+
if __name__ == '__main__':
60+
main()
61+
62+
63+

0 commit comments

Comments
(0)

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