自学内容网 自学内容网

Leetcode215. 数组中的第K个最大元素

我们也可以使用堆排序来解决这个问题——建立一个小根堆,

遍历数组将元素入堆;如果当前堆内元素超过 k 了,我们就把堆顶元素去除,即去除当前的最小值。因此我们在元素入堆的过程中,不断淘汰最小值,最终留在堆中就是数组中前 k 个最大元素,并且堆顶元素为前 k 大元素中的最小值,即为第 k 个元素。

所以代码很简洁:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) 
    {
        priority_queue<int,vector<int>,greater<int>> aa;
        for(auto & e :nums)
        {
            aa.push(e);
            if(aa.size()>k)
            aa.pop();
        }
        return aa.top();    
    }
};


原文地址:https://blog.csdn.net/2301_80017277/article/details/140596001

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!