LeetCode Problem 215: Kth Largest Element in an Array
Given an integer array nums
and an integer k
, return the kth
largest element in the array.
Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
k
be larger than the length of the array?
A: No, k
will always be a valid integer such that 1 <= k <= len(nums)
.To find the kth
largest element in an array, there are several possible approaches:
kth
largest element directly.k
to keep track of the k
largest elements encountered so far.Here, we’ll use the Heap approach for its balanced performance and ease of implementation:
k
to keep track of the largest elements.
k
, we simply add the current element.k
, we compare the current element with the smallest element in the heap (heap root). If the current element is larger, we replace the smallest element with the current element.kth
largest element in the end.k
, push the element onto the heap.kth
largest element.import heapq
def findKthLargest(nums, k):
min_heap = []
for num in nums:
if len(min_heap) < k:
heapq.heappush(min_heap, num)
else:
if num > min_heap[0]:
heapq.heapreplace(min_heap, num)
return min_heap[0]
# Example usage
nums = [3,2,1,5,6,4]
k = 2
print(findKthLargest(nums, k)) # Output: 5
O(k)
time.O(log k)
time. For n
elements, this results in O(n log k)
time.Overall time complexity: O(n log k)
. This is efficient for large arrays combined with reasonably-sized k
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?