Advertisement
smj007

Find Kth largest element in an array

Aug 17th, 2024
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. # TC : avg O(N) worst O(N^2)
  2. # SC : O(log N) worst O(N)
  3.  
  4. class Solution:
  5.     def findKthLargest(self, nums: List[int], k: int) -> int:
  6.         def quickselect(left, right):
  7.  
  8.             # random selection of pivot and move to right
  9.             pidx = random.randint(left, right)
  10.             pivot = nums[pidx]
  11.             nums[pidx], nums[right] = nums[right], nums[pidx]
  12.  
  13.             # p to track where the next larger element should go
  14.             p, pivot = left, nums[right]
  15.             for i in range(left, right):
  16.                 # notice i always moves faster than p
  17.                 if nums[i] >= pivot:
  18.                     nums[i], nums[p] = nums[p], nums[i]
  19.                     p += 1
  20.  
  21.             nums[p], nums[right] = nums[right], nums[p]
  22.  
  23.             if k < (p + 1):
  24.                 return quickselect(left, p-1)
  25.             elif k > (p + 1):
  26.                 return quickselect(p+1, right)
  27.             else:
  28.                 return nums[p]
  29.  
  30.         return quickselect(0, len(nums)-1)
  31.  
  32. # TC : avg O(N) worst O(N^2)
  33. # SC : O(log N) worst O(N)
  34. class Solution:
  35.     def findKthLargest(self, nums: List[int], k: int) -> int:
  36.  
  37.         def quickselect(left, right):
  38.  
  39.             # random selection of pivot and move to right
  40.             pidx = random.randint(left, right)
  41.             pivot = nums[pidx]
  42.             nums[pidx], nums[right] = nums[right], nums[pidx]
  43.  
  44.             # p to track where the next larger element should go
  45.             p, pivot = left, nums[right]
  46.             for i in range(left, right):
  47.                 # notice i always moves faster than p
  48.                 if nums[i] <= pivot:
  49.                     nums[i], nums[p] = nums[p], nums[i]
  50.                     p += 1
  51.  
  52.             nums[p], nums[right] = nums[right], nums[p]
  53.  
  54.             if k < (p + 1):
  55.                 return quickselect(left, p-1)
  56.             elif k > (p + 1):
  57.                 return quickselect(p+1, right)
  58.             else:
  59.                 return nums[p]
  60.  
  61.         k = len(nums) - k + 1
  62.         return quickselect(0, len(nums)-1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement