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

相关推荐

  1. 215数组K元素

    2024-07-22 05:38:01       47 阅读
  2. leetcode-215-数组K元素

    2024-07-22 05:38:01       41 阅读
  3. LeetCode215. 数组K元素

    2024-07-22 05:38:01       32 阅读
  4. LeetCode-热题100:215. 数组K元素

    2024-07-22 05:38:01       31 阅读
  5. Leetcode215_数组K元素

    2024-07-22 05:38:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 05:38:01       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 05:38:01       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 05:38:01       45 阅读
  4. Python语言-面向对象

    2024-07-22 05:38:01       55 阅读

热门阅读

  1. android audio 相机按键音:(一)资源加载与替换

    2024-07-22 05:38:01       17 阅读
  2. 使用 Jenkins 实现持续集成和持续部署(CI/CD)

    2024-07-22 05:38:01       11 阅读
  3. TiDB热点问题

    2024-07-22 05:38:01       18 阅读
  4. setup中如何获取组件实例

    2024-07-22 05:38:01       17 阅读
  5. 编程中的智慧五:工厂设计模式

    2024-07-22 05:38:01       20 阅读
  6. 模型瘦身术:目标检测中的剪枝与量化

    2024-07-22 05:38:01       18 阅读
  7. 前端面试题日常练-day100 【Less】

    2024-07-22 05:38:01       15 阅读
  8. C++顶层const和底层const

    2024-07-22 05:38:01       17 阅读
  9. HOW - React 处理不紧急的更新和渲染

    2024-07-22 05:38:01       18 阅读