215. 数组中的第K个最大元素(leetcode)

输入: [3,2,1,5,6,4] 和 k = 2



输入: [3,2,3,1,2,4,5,5,6] 和 k = 4

class Solution {
public:

void quick_sort(vector<int> &nums, int left, int right, int k)
{
int start = left;
int end = right;
int base = nums[left];
int tmp_index = left;
while (right > left)
{
while (right > left && nums[right] >= base)
{
right--;
}

nums[left] = nums[right];
tmp_index = right;

while (right > left && nums[left] <= base)
{
left++;
}

nums[right] = nums[left];
tmp_index = left;
nums[tmp_index] = base;

}
//全部排序
// if (end - tmp_index > 1)
// {
//     quick_sort(nums,tmp_index + 1, end, k, result);
// }
// if (tmp_index - start > 1)
// {
//     quick_sort(nums, start, tmp_index - 1, k, result);
// }

//有条件的进行排序
if (tmp_index == nums.size() - k)
{
return;
}
else if (tmp_index <= nums.size() - k)
{
if (end - tmp_index > 1)
{
quick_sort(nums,tmp_index + 1, end, k);
}
}
else
{
if (tmp_index - start > 1)
{
quick_sort(nums, start, tmp_index - 1, k);
}
}
}

int findKthLargest(vector<int>& nums, int k) {

quick_sort(nums, 0, nums.size() - 1, k);

return nums[nums.size() - k];
}
};