描述
给定一个整数数组,同时给定它的大小n和要找的k,请根据快速排序的思路,找出数组中第k大的数
输入:
[1,3,5,2,2],5,3
返回值:2
要求:时间复杂度 O(nlogn)O(nlogn),空间复杂度 O(1)O(1)
解题思路
方法一:sort函数排序
本题是一个排序问题,可选的排序方案很多,其中冒泡、选择等O(n^2)时间的排序方案代价较高,选用快排、堆排、分治算法是比较省时的方案。直接调用c++内置sort函数是最好的办法。
class Solution {
public:
static bool cmp(const int& a, const int& b) { // 设定比较规则,大数靠前
return a > b;
}
int findKth(vector<int> a, int n, int K) {
// write code here
sort(a.begin(), a.end(), cmp); // 将原数组重新排序
return a[K-1]; // 返回第k大的数字
}
};
时间复杂度:O(NlogN),排序时间
空间复杂度:O(1),没有申请额外空间
方法二:堆排序
构建一个大小为k的小顶堆,在小顶堆中,存储着k个较大的元素,根是这k个中最小的,如果出现比根还要大的元素,说明可以替换根
class Solution {
public:
int findKth(vector<int> a, int n, int K) {
priority_queue<int,vector<int>,greater<int>> pq;//构建小根堆,升序队列
for(int num: a){
if(pq.size()<K) pq.push(num);
else{
if (num > pq.top()) {
pq.pop();
pq.push(num);
}
}
}
return pq.empty() ? 0 : pq.top();
}
};