Jayakrishna14

Kth-largest

Aug 28th, 2024
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int QuickSortIndex(vector<int>& nums, int i, int j){
  4.         int pivot = i;
  5.  
  6.         while(i <= j){
  7.             while(i<nums.size() && nums[i] <= nums[pivot]){
  8.                 i++;
  9.             }
  10.  
  11.             while(j >= 0 && nums[j] > nums[pivot]){
  12.                 j--;
  13.             }
  14.  
  15.             if(i <j ){
  16.                 swap(nums[i], nums[j]);
  17.             }
  18.         }
  19.  
  20.         swap(nums[j], nums[pivot]);
  21.         return j;
  22.     }
  23.  
  24.  
  25.     int findKthLargest(vector<int>& nums, int k) {
  26.         int i=0, j=nums.size()-1;
  27.         while(i<=j){
  28.             int pivot = QuickSortIndex(nums, i, j);
  29.             if(pivot == nums.size()- k){
  30.                 return nums[pivot];
  31.             }
  32.  
  33.             if(pivot > nums.size() - k){
  34.                 j = pivot - 1;
  35.             }
  36.             else{
  37.                 i = pivot + 1;
  38.             }
  39.         }
  40.  
  41.         return -1;
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment