Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
思路均来自《编程之美》
方法一:
选择排序找出前k个最大的,复杂度O(n*k)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
for(int i = 0; i < k; i++){ // O(n*k)
int maxId = i;
for(int j = i+1; j < n; j++){
if(nums[j] > nums[maxId]) maxId = j;
}
swap(nums[i], nums[maxId]);
}
return nums[k-1];
}
};
方法二:
O( n log n )排序之后输出第k大的,和方法一的复杂度比较要看K和log n 谁大谁小
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
sort(nums.rbegin(), nums.rend());
return nums[k-1];
}
};
方法三:
利用快速排序partition的思想,每次把不小于pivot的数放左边,小于pivot的数放右边。最后判断一下pivot的下标与k-1的关系,然后返回pivot或者缩小范围继续递归。时间复杂度为O( n log k)? 好像是O(n)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return helper(nums, 0, nums.size()-1, k);
}
private:
int helper(vector<int>& nums, int s, int e, int k){
int lastLarge = s; // pivot is nums[s]
for(int i = s+1; i <= e; i++){
if(nums[i] >= nums[s])
swap(nums[++lastLarge], nums[i]);
} swap( nums[s], nums[lastLarge]);
if(lastLarge == k-1) return nums[lastLarge];
if(lastLarge < k) return helper(nums, lastLarge+1, e, k); // lastLarge < k-1
return helper(nums, s, lastLarge-1, k); // lastLarge >= k
}
};
方法四:
条件允许可以改为桶排序,本题输入的数据范围不明确所以不能使用。n个正整数范围[0, MAXN-1], count[i]用来代表 i出现了count[i]次
for(sumCount = 0, i = MAXN-1; i>= 0; i--){
sumCount += count[i];
if(sumCount >= k) return i;
}