LeetCode 215
Kth Largest Element in an Array
class Solution {
public:
int Partition(vector<int>& nums, int low, int high) {
int pivot = nums[low];
while(low<high) {
while(low<high && nums[high]>= pivot) high--;
nums[low] = nums[high];
while(low<high && nums[low]<= pivot) low++;
nums[high] = nums[low];
}
nums[low] = pivot;
return low;
}
int findKthLargest(vector<int>& nums, int k) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
k = nums.size()-k;
int low = 0, high = nums.size()-1;
while(low<high) {
int pivot = Partition(nums, low, high);
if (pivot == k) {
break;
} else if (pivot<k) {
low = pivot+1;
} else {
high = pivot-1;
}
}
return nums[k];
}
};