215. Kth Largest Element in an Array

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

Note that it is the kth largest element in the sorted order, not the kth distinct element.

You must solve it in O(n) time complexity.

 

Example:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5


def findKthLargest(nums: List[int], k: int):
       
    heap = nums[:k]
    heapq.heapify(heap)        
    N = len(nums)

    for i in range(k, N):            
        heapq.heappush(heap, nums[i])                      
        heapq.heappop(heap)
       
    return heap[0]

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break