Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- Basically we have to find the Kth largest element in array of size n that will be the (n-k)th element if we
- sort that array.
- so,we will select an element for pivot(last element) and find it's actual position in sorted array.
- using partition function and compare that position with k if same then that is our actual element else
- we will check,
- if k is in left of that position,pass the left array in partition else right.
- */
- int partition(vector <int> &arr,int l,int r){
- int pivot=arr[r],i=l;
- for(int j=l;j<r;j++){ //it basically put all the smaller element than pivot in left and bigger in right.
- if(arr[j]<=pivot) swap(arr[j],arr[i++]);
- }
- swap(arr[i],arr[r]); //put the pivot element at it's actual position.
- return i; //return the acutal position of pivot element.
- }
- int fun(vector <int> &arr,int l,int r,int k){
- int i=partition(arr,l,r);
- if(i==k) return arr[i];
- else if(k<i){
- return fun(arr,l,i-1,k);
- }
- else{ //k>i
- return fun(arr,i+1,r,k);
- }
- }
- class Solution {
- public:
- int findKthLargest(vector<int>& nums, int k) {
- return fun(nums,0,nums.size()-1,nums.size()-k);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement