imashutosh51

Kth largest Element

Oct 8th, 2022 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. '''
  2. Logic:
  3. Basically we have to find the Kth largest element in array of size n that will be the (n-k)th element if we
  4. sort that array.
  5. so,we will select an element for pivot(last element) and find it's actual position in sorted array.
  6. using partition function and compare that position with k if same then that is our actual element else
  7. we will check,if k is in left of that position,pass the left array in partition else right.
  8. This fails in the sorted long array and gives the O(N*N) as you take pivot as last element and everytime put it into it's posiiton and iterate all elements for each pivot.
  9. '''
  10.  
  11. def partition(arr,l,r):
  12.     pivot=arr[r]
  13.     k=l
  14.     i=l
  15.     while i<r:
  16.         if arr[i]<arr[r]:
  17.             arr[k],arr[i]=arr[i],arr[k]
  18.             i+=1
  19.             k+=1
  20.         else:
  21.             i+=1
  22.     arr[k],arr[r]=arr[r],arr[k]
  23.     return k
  24.  
  25. def quick_select(arr,l,r,k):
  26.     if l<=r:
  27.         p=partition(arr,l,r)
  28.         if p==k:
  29.             return arr[p]
  30.         if p<k:
  31.             return quick_select(arr,p+1,r,k)
  32.         else:
  33.             return quick_select(arr,l,p-1,k)
  34.  
  35. class Solution:
  36.     def findKthLargest(self, nums: List[int], k: int) -> int:
  37.         k=len(nums)-k
  38.         return quick_select(nums,0,len(nums)-1,k)
  39.  
  40.  
  41. M-2: Use the Min heap approach. T.C O(Nlog(k))
  42. from heapq import heapify,heappush,heappop
  43. class Solution:
  44.     def findKthLargest(self, nums: List[int], k: int) -> int:
  45.         heap=[]
  46.         for i in nums:
  47.             if len(heap)<k:
  48.                 heappush(heap,i)
  49.             elif heap[0]<i:
  50.                 heappop(heap)
  51.                 heappush(heap,i)
  52.         return heap[0]
Advertisement
Add Comment
Please, Sign In to add comment