-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth_largest.py
More file actions
40 lines (28 loc) · 850 Bytes
/
kth_largest.py
File metadata and controls
40 lines (28 loc) · 850 Bytes
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
import heapq
class Solution:
def kthLargestEfficient(self, nums, k):
heap = []
for num in nums:
if len(heap) < k:
heapq.heappush(heap, num)
elif num > heap[0]:
heapq.heappushpop(heap, num)
return heap[0]
# Time Complexity: O(n log k)
# Space Complexity: O(k)
def kthLargest(self, nums, k):
nums = [-num for num in nums]
heapq.heapify(nums)
for _ in range(k - 1):
heapq.heappop(nums)
return -heapq.heappop(nums)
# Time Complexity: O(n + log k)
# Space Complexity: O(n)
if __name__ == "__main__":
solution = Solution()
nums = [5, 3, 2, 1, 4]
k = 2
result = solution.kthLargest(nums, 2)
assert result == 4
print(result)
print("Test Case 1 Passed!")