题目描述
在一个无序数组中找出第k大的元素。
思路
方法一: 排序,取第k个,O(nlogn)
方法二: 最小堆,维护最大k个元素的最小堆,堆顶元素不断和数组中剩余元素比较,如果堆顶元素小于数组元素,替换堆顶,并维护堆。O(nlogk)
方法三: 在快排过程中,不断返回标杆的位置,如果左边区间元素个数>k,那么在左区间继续寻找,否则在右区间寻找 (k-左区间元素个数)。时间复杂度接近 O(n)
代码
方法二:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
int n = nums.size();
int cnt = 0;
for (; cnt<k; ++cnt) pq.push(nums[cnt]);
while(cnt < n) {
if (nums[cnt] < pq.top()) {
cnt++;
continue;
}
pq.pop();
pq.push(nums[cnt]);
cnt++;
}
return pq.top();
}
};
方法三:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
return findKth(nums, 0, n-1, k);
}
int partitions(vector<int>& nums, int l, int r) {
int key = nums[l];
int i = l;
int j = r;
while(i < j) {
while(i < j && nums[j] < key) j--;
if (i < j) nums[i++] = nums[j];
while(i < j && nums[i] >= key) i++;
if (i < j) nums[j--] = nums[i];
}
nums[i] = key;
return i;
}
int findKth(vector<int>& nums, int l, int r, int k) {
if (l == r) return nums[l];
int p = partitions(nums, l, r);
cout << p << endl;
int cnt = p - l + 1;
if (cnt == k) {
return nums[p];
}else if (cnt > k) {
return findKth(nums, l, p-1, k);
}else {
return findKth(nums, p+1, r, k-cnt);
}
}
};