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());
}
};

本文介绍了一种在未排序数组中查找第K大元素的有效算法。通过快速排序思想的变体实现O(n)时间复杂度,以及使用大顶堆或多集合实现O(nlogk)时间复杂度的方法。
887

被折叠的 条评论
为什么被折叠?



