⭐️ 题目描述
🌟 leetcode链接:数组中第k大的元素
思路:
使用堆数据结构,大堆的堆顶是堆内最大的元素,也就是把当前堆 pop
k - 1
次,第 k
次 top
出来的元素就是第 k
大的数。文章来源:https://www.toymoban.com/news/detail-706938.html
代码:文章来源地址https://www.toymoban.com/news/detail-706938.html
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
// Top-k 问题
// 使用大堆 top 出 k - 1 次 再 top 一次就是 第k大的数
priority_queue heap(nums.begin() , nums.end()); // 默认是大堆
while (--k) {
heap.pop();
}
return heap.top();
}
};
到了这里,关于leetcode 215.数组中第k大的元素的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!