Advertisement
smj007

Kth largest element in an array

Aug 20th, 2024
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. # O(k) + (n-k)logK = nlogk
  2. # O(k)
  3. class Solution:
  4.     def findKthLargest(self, nums: List[int], k: int) -> int:
  5.  
  6.         # convert this problem of converting to find the minium among
  7.         # k largest element in a list
  8.         heap = [x for x in nums[:k]]
  9.         heapq.heapify(heap)
  10.  
  11.         # Wrong
  12.         # for i in range(k, len(nums)-1):
  13.         # Right
  14.         for i in range(k, len(nums)):
  15.             # sinve we are trying to keep the k-largest numbers in the heap
  16.             # we will add any incoming element that is the larger than the min
  17.             # of the heap. Because our goal is to have as many large elements
  18.             # in the heap
  19.             if heap and heap[0] < nums[i]:
  20.                 heapq.heappop(heap)
  21.                 heapq.heappush(heap, nums[i])
  22.  
  23.         return heap[0]
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement