- Link: 215. Kth Largest Element in an Array - Medium
- Track: NeetCode150
Question
Restate the problem
- Given an integer array
numsand an integerk - Return the
kthlargest element in the array - Note:
- it is the
kthlargest in sorted order - not the
kthdistinct element
- it is the
Edge Case
k = len(nums)→ return the smallest element
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Heap |
Method 1
Key idea:
Build a max heap, then popktimes. The last popped value is thekthlargest.
先用 heap 建一个最大堆,然后弹出k次,最后一次弹出的值就是第k大。
Approach
- Python
heapqis a min heap - To simulate a max heap, push
-numinto the heap - Pop from the heap
ktimes - The last popped value is the kth largest element
Complexity
- Time Complexity:
- Space Complexity:
Code
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
max_heap = []
for num in nums:
heapq.heappush(max_heap, -num)
while k and max_heap:
val = heapq.heappop(max_heap)
k -= 1
return -valMistake
- Forget to convert back at the end: return
-val