Created
February 27, 2018 06:38
-
-
Save tamarous/d78b83f25e4294dbcbab7e977e810623 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 findKthLargest(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 (i == k - 1) { | |
return nums[i]; | |
} else if (i > k-1) { | |
high = i - 1; | |
} else { | |
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