Kth Largest Element in an Array

LeetCode

LeetCode: https://leetcode.com/problems/kth-largest-element-in-an-array/

Given an integer array nums and an integer k, return the kth largest element in the array.

1import heapq
2
3def findKthLargest(nums: List[int], k: int) -> int:
4 heap = []
5 for x in nums:
6 heapq.heappush(heap, x)
7 if len(heap) > k:
8 heapq.heappop(heap)
9 return heap[0]
i
3
0
2
1
1
2
5
3
6
4
4
5
k=2
Step 1 / 3
Step 1:
Maintain a min-heap of size k while scanning nums.
Pointers: i=0
Focus: select @ [0]
k=2