Last active
February 27, 2018 06:37
-
-
Save tamarous/e17559d9e020aee33066aecb4d49f781 to your computer and use it in GitHub Desktop.
寻找数组中第k小的元素
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int quickSelect(vector<int> &nums, int k) { | |
int lo = 0; | |
int high = (int)nums.size() - 1; | |
for(; lo < high; ) { | |
int i = lo, j = high; | |
int pivot = nums[lo]; | |
while(i < j) { | |
while( i < j && pivot <= nums[j]) { | |
j--; | |
} | |
nums[i] = nums[j]; | |
while(i < j && pivot >= nums[i]) { | |
i++; | |
} | |
nums[j] = nums[i]; | |
} | |
nums[i] = pivot; | |
if (k <= i) { | |
high = i - 1; | |
} | |
if (i <= k) { | |
lo = i + 1; | |
} | |
} | |
return nums[k-1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment