Skip to content

Commit f940d40

Browse files
authored
Update kth-largest-element-in-an-array.py
Solution 3 using heapq library
1 parent 1cf2e37 commit f940d40

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Python/kth-largest-element-in-an-array.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,21 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums):
7272
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
7373
return new_pivot_idx
7474

75+
"""
76+
This implementation maintains a min-heap of size k, ensuring that the smallest element in the heap is the k-th largest in the array.
77+
The time complexity is O(Nlogk), which is efficient for large arrays.
78+
"""
79+
80+
import heapq
81+
class Solution3(object):
82+
def findKthLargest(self, nums: List[int], k: int) -> int:
83+
# Create a min-heap with the first k elements
84+
min_heap = nums[:k]
85+
heapq.heapify(min_heap)
86+
87+
# Iterate through the remaining elements
88+
for num in nums[k:]:
89+
if num > min_heap[0]: # Compare with the smallest element in the heap
90+
heapq.heappushpop(min_heap, num) # Push new element and pop the smallest
91+
92+
return min_heap[0] # The root of the heap is the k-th largest element

0 commit comments

Comments
 (0)