Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int k;
- public:
- int q_partition(vector<int> & nums, int k, int l, int r_pivot) {
- int pivot = nums[r_pivot];
- int i = k;
- int j = k;
- int z = l;
- while (i <= l && j <= z) {
- bool enteredBelowLoop = false;
- while (nums[j] == pivot && z>=0 && j <= z) {
- swap(nums[j], nums[z]);
- z--;
- enteredBelowLoop = true;
- }
- if(enteredBelowLoop){
- continue;
- }
- if (nums[j] < pivot) {
- swap(nums[i], nums[j]);
- i++;
- j++;
- } else {
- j++;
- }
- }
- int to_return = -1;
- //now my j points to the position I can start putting my pivot at
- z++;
- while (z <= l) {
- swap(nums[i], nums[z]);
- if (to_return == -1) to_return = i;
- i++;
- z++;
- }
- return to_return;
- }
- int quickSort(vector < int > & nums, int i, int j) {
- int r_pivot = i + (rand() % (j - i + 1));
- int pIndex = q_partition(nums, i, j, r_pivot);
- if (pIndex == nums.size() - k) {
- return nums[pIndex];
- }
- if (pIndex < nums.size() - k) {
- return quickSort(nums, pIndex + 1, j);
- }
- return quickSort(nums, i, pIndex - 1);
- }
- int findKthLargest(vector < int > & nums, int tempK) {
- k = tempK;
- return quickSort(nums, 0, nums.size() - 1);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement