215. Kth Largest Element in an Array
Description:
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.
Difficulty:Medium
Example:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
方法1:sort
- Time complexity : O ( n l o g n ) O\left ( nlogn\right ) O(nlogn)
- Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end(), [](const int& a, const int& b) {return a > b; });
return nums[k - 1];
}
};
方法2:min-heap
- Time complexity : O ( n l o g k ) O\left ( nlogk\right ) O(nlogk)
- Space complexity :
O
(
k
)
O\left ( k \right )
O(k)
思路:
维护k大小的最小堆,到最后的top便是结果
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int> > pq;
for (auto num : nums) {
pq.push(num);
if (pq.size() > k)
pq.pop();
}
return pq.top();
}
};
方法3:Quick select
- Time complexity : O ( n ) O\left ( n\right ) O(n)
- Space complexity :
O
(
1
)
O\left ( 1 \right )
O(1)
思路:
利用快排中的partition,比快排要少一半的操作,因为每次左右两边的递归只运行一个即可。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left = 0, right = nums.size() - 1;
while (true) {
int p = partition(nums, left, right);
if (p == k - 1) {
return nums[p];
}
if (p > k - 1) {
right = p - 1;
} else {
left = p + 1;
}
}
}
int partition(vector<int>& nums, int left, int right){
int pivot = nums[left], l = left+1, r = right;
while(true){
while(l <= right && nums[l] > pivot) l++;
while(left+1 <= r && nums[r] < pivot) r--;
if(l > r) break;
swap(nums[l++], nums[r--]);
}
swap(nums[left], nums[r]);
return r;
}
};