大根堆解法:
时间复杂度O(K*lgN),空间复杂度O(K)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> q;
//将所有元素加入大根堆
for (int i = 0; i < nums.size(); ++i) {
q.push(nums[i]);
}
//出K - 1次堆顶元素
for (int i = 0; i < k - 1; ++i) {
//每一次出一个堆顶元素就需要建堆
q.pop();
}
return q.top();
}
};
快速选择解法
时间复杂度O(N),空间复杂度O(1)
class Solution {
public:
//寻找nums[low]在数组中的位置
int getPartionPos(vector<int>& nums, int low, int high)
{
int key = nums[low];
while (low < high) {
while (low < high && nums[high] >= key) {
--high;
}
nums[low] = nums[high];
while (low < high && nums[low] <= key) {
++low;
}
nums[high] = nums[low];
}
nums[high] = key;
return high;
}
int findKthLargest(vector<int>& nums, int k) {
int KthLargestPos = nums.size() - k;
int i = 0;
int j = nums.size() - 1;
while (i < j) {
int currPos = getPartionPos(nums, i, j);
if (currPos < KthLargestPos) {
i = currPos + 1;
} else if (currPos > KthLargestPos) {
j = currPos - 1;
} else {
break;
}
}
return nums[KthLargestPos];
}
};