快速排序找 topk
int quickSort(vector<int>&arr, int left, int right, int k)
{
int i = left, j = right;
//随机选择基准值
int ran = (rand() % (right - left + 1)) + left;
swap(arr[ran], arr[left]);
//基准值即arr[left]
while (i < j)
{
while (i < j&&arr[j] >= arr[left])--j;//从后往前找小于基准值的数
while (i < j&&arr[i] <= arr[left])++i;//从前往后找大于基准值的数
swap(arr[i], arr[j]);
}
swap(arr[left], arr[i]);//确定基准值位置
if (i > k)return quickSort(arr, left, i - 1, k);//若i>k则第k小的数在基准值左边,递归左边
if (i < k)return quickSort(arr, i + 1, right, k);//类似
return arr[k];//若i==k则返回
}
int findKthLargest(vector<int>& nums, int k) {
return quickSort(nums, 0, nums.size() - 1, nums.size() - k);//倒数第k大:size-k 相当于第size-k小
}
优先队列找topk
int findKthLargest(vector<int>& nums, int k)
{
priority_queue<int, vector<int>, greater<int>> minHeap;
for (int i = 0; i < k; ++i)
{
minHeap.push(nums[i]);
}
for (int i = k; i < nums.size(); ++i)
{
if (nums[i] > minHeap.top())
{
minHeap.pop();
minHeap.push(nums[i]);
}
}
return minHeap.top();
}