Problem: 215. 数组中的第K个最大元素
题目描述
思路
1.维护一个小顶堆minHeap,并将数组nums中的前k个元素添加到minHeap中;
2.从nums中k后面的元素开始,若当前nums中的元素大于小顶堆中的堆顶元素,则将其minHeap中堆顶的元素取出,将当前的nums中的元素添加到minHeap中
3.返回最终的minHeap堆顶的元素即为第K大元素;
复杂度
时间复杂度:
O ( n l o g n ) O(nlogn) O(nlogn);其中 n n n是数组的大小
空间复杂度:
O ( n ) O(n) O(n)
Code
class Solution {
public:
int findKthLargest(std::vector<int>& nums, int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
for (int i = 0; i < k; ++i) {
minHeap.push(nums[i]);
}
// Starting from k, compare nums[i] with the top of the heap each time
for (int i = k; i < nums.size(); i++) {
int topElement = minHeap.top();
// If it is larger than the top of the heap, the top of the heap element
// is removed from the queue and the top element is rejoined.
if (nums[i] > topElement) {
minHeap.pop();
minHeap.push(nums[i]);
}
}
// Returns the smallest value in the smallest
// heap of the largest k elements of the natural order
return minHeap.top();
}
};