Advertisement
imashutosh51

Kth largest Element

Oct 8th, 2022
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 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,
  8. if k is in left of that position,pass the left array in partition else right.
  9.  
  10. */
  11.  
  12. int partition(vector <int> &arr,int l,int r){
  13.     int pivot=arr[r],i=l;
  14.     for(int j=l;j<r;j++){  //it basically put all the smaller element than pivot in left and bigger in right.
  15.         if(arr[j]<=pivot) swap(arr[j],arr[i++]);
  16.     }
  17.     swap(arr[i],arr[r]);   //put the pivot element at it's actual position.
  18.     return i;              //return the acutal position of pivot element.
  19. }
  20. int fun(vector <int> &arr,int l,int r,int k){
  21.         int i=partition(arr,l,r);
  22.         if(i==k) return arr[i];
  23.         else if(k<i){
  24.             return fun(arr,l,i-1,k);
  25.         }
  26.         else{   //k>i
  27.             return fun(arr,i+1,r,k);
  28.         }
  29. }
  30. class Solution {
  31. public:
  32.     int findKthLargest(vector<int>& nums, int k) {
  33.         return fun(nums,0,nums.size()-1,nums.size()-k);
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement