215. 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.
Example 1:
Input: [3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
題目鏈接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
思路
法一:快排思想
只做一半的快排,複雜度O(n)。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
if(nums.size()<k) return -1;
return findk(nums, k, 0, nums.size()-1);
}
int findk(vector<int>& nums, int k, int left, int right){
if(left==right) return nums[left];
int l = left, r = right, key = nums[left];
while(l<r){
while(l<r && nums[r]<key){
--r;
}
if(l<r){
nums[l++] = nums[r];
}
while(l<r && nums[l]>key){
++l;
}
if(l<r){
nums[r--] = nums[l];
}
}
nums[l] = key;
if(l==k-1) {
return key;
} else if(l<k-1 ) {
return findk(nums, k, l+1, right);
}else{
return findk(nums, k, left, l-1);
}
}
};
法二:大/小頂堆
維護k大小的大頂堆,複雜度O(nlogk)。
可選容器:multiset,priority_queue。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
multiset<int> ms;
for(int i=0; i<nums.size();++i){
if(ms.size()<k){
ms.insert(nums[i]);
}else{
if(nums[i]>*(ms.begin())){
ms.erase(ms.begin());
ms.insert(nums[i]);
}
}
}
return *(ms.begin());
}
};