2025-09-10 12:09
Status: child
Tags: leetcode leetcode-medium Leetcode heaps Heaps Intro
Kth Largest Element in an Array
Code
import heapq
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# max heap
heap = []
for num in nums:
if len(heap) < k:
heapq.heappush(heap, num)
else:
heapq.heappushpop(heap, num)
return heap[0]
Explanation
- Just like K Closest Points to Origin without the distance calculations
- Iterate through nums, and if the heap length is less than k, well push
- Else: heappushpop the current num
- Return the first element in heap(heap[0])