系列专栏
双指针
模拟算法
分治思想
目录
1、题目链接
215. 数组中的第K个最大元素 - 力扣(LeetCode)
2、题目介绍
给定整数数组 nums
和整数 k
,请返回数组中第 k
个最大的元素。
请注意,你需要找的是数组排序后的第 k
个最大的元素,而不是第 k
个不同的元素。
你必须设计并实现时间复杂度为 O(n)
的算法解决此问题。
3、解法
4、代码
class Solution {
public:
//向下调整
//降序版
void AdjustDown(vector<int>& nums, int n, int parent)
{
//子节点必须在不越界。 child < nums.size()
int child = parent * 2 + 1;
while (child < n)
{
// 确认child指向小的那个孩子
if (child + 1 < n && nums[child + 1] < nums[child])
{
++child;
}
if (nums[parent] > nums[child])
{
swap(nums[parent], nums[child]);
parent = child;
child = parent * 2 + 1;
}
else
break;
}
}
//降序建小堆
void HeapSort(vector<int>& nums) {
//从叶子结点建堆
for (int i = (nums.size() - 1 - 1) / 2; i >= 0; i--)
{
AdjustDown(nums, nums.size(), i);
}
int end = nums.size() - 1;
while (end > 0)
{
swap(nums[0], nums[end]);
AdjustDown(nums, end, 0);
--end;
}
}
int findKthLargest(vector<int>& nums, int k) {
HeapSort(nums);
return nums[k-1];
}
};