Leetcode 215 Kth Largest Element in an Array
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
- You can build a heap from input array and pop the heap until there k element left. Building heap is taking O(nlogn) time complexity.
def findKthLargest(self, nums: List[int], k: int) -> int:
heapq.heapify(nums)
amount = len(nums)
while amount > k:
heapq.heappop(nums)
amount -= 1
return nums[0]