Skip to content

Kth Largest Element in an Array

LeetCode

01 · Question

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

02 · Solution

Reference solution

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]