Guest User

Untitled

a guest
Oct 22nd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int findKthLargest(vector<int>& nums, int k) {
  4. return quickSelect(nums, 0, nums.size() - 1, k);
  5. }
  6.  
  7. private:
  8. int quickSelect(vector<int>& nums, int lo, int hi, int k)
  9. {
  10. if(lo == hi)return nums[lo];
  11. int num = nums[lo], i = lo + 1, j = hi;
  12. while(true)
  13. {
  14. while(i <= hi && nums[i] >= num)++i;
  15. while(j > lo && nums[j] <= num)--j;
  16. if(i > j)break;
  17. swap(nums[i], nums[j]);
  18. }
  19. swap(nums[lo], nums[j]);
  20. if(k == j + 1 - lo)return nums[j];
  21. else if(k < j + 1 - lo)return quickSelect(nums, lo, j - 1, k);
  22. else return quickSelect(nums, j + 1, hi, k - (j + 1 - lo));
  23. }
  24. };
Add Comment
Please, Sign In to add comment