题目:给定整数数组 nums
和整数 k
,请返回数组中第 k
个最大的元素。
方法:
1.完全排序,即快排
时间复杂度:平均O(N*logN),最坏O(N^2)
2.部分排序,STL中的std::partial_sort
时间复杂度:最坏O(N*logK)
3.快速选择
时间复杂度:平均 O(N),最坏 O(N^2)
4.BFPRT
时间复杂度:平均 O(N),最坏 O(N)
5.堆排序:小根堆vs大根堆
大根堆:
时间复杂度:O(n log n)。其中建堆时间O(n),把大顶放后面的时间O(k log n)
class Solution {
public:
//从curIdx开始的一次向下调整
void maxHeapify(vector<int>& nums, int curIdx, int heapSize) {
//左右孩子的下标
int leftIdx = curIdx * 2 + 1, rightIdx = curIdx * 2 + 2;
//maxIdx是记录三者中最大值的下标
int maxIdx = curIdx;
//三者比较
if(leftIdx < heapSize && nums[leftIdx] > nums[maxIdx])
maxIdx = leftIdx;
if(rightIdx < heapSize && nums[rightIdx] > nums[maxIdx])
maxIdx = rightIdx;
//交换
if(maxIdx != curIdx) {
swap(nums[maxIdx], nums[curIdx]);
//如果下面还有小顶堆的情况,处理下面
maxHeapify(nums, maxIdx, heapSize);
}
}
//大顶堆
void buildMaxHeap(vector<int>& nums, int heapSize) {
for(int i = heapSize / 2; i >= 0; i--) {
maxHeapify(nums, i, heapSize);
}
}
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
int heapSize = n;
//建堆
buildMaxHeap(nums, heapSize);
//取k次堆顶,把第k大之前的大顶都放后面
for(int i = n - 1; i >= n - k + 1; i--) {
swap(nums[0], nums[i]);
//通过缩减heapSize来忽略大顶
--heapSize;
maxHeapify(nums, 0, heapSize);
}
return nums[0];
}
};
6.二叉搜索树