• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
kulukulu
博客园    首页    新随笔    联系   管理    订阅  订阅
leetcode 703数据流中的第K大元素

这里思路是堆排序,而且是小根堆。C++中包含在头文件<queue>的priority_queue本质就是堆排序实现的。其中priority_queue函数原型是

priority_queue<Type, Container, Functional> 

       Type 就是数据类型,
       Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),
       Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大根堆 。
 
//降序队列(大根堆)
priority_queue <int,vector<int>,less<int> >q;
 
//升序队列(小根堆)
priority_queue <int,vector<int>,greater<int> > q;
 
另外,greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
本题代码如下:
class KthLargest {
private:
     priority_queue<int, vector<int>, greater<int>> heap;
     int size;
public:
    KthLargest(int k, vector<int> nums) {
       size=k;
        for (int i = 0; i < nums.size(); i++){            
            heap.push(nums[i]);
           if(heap.size()>k)  heap.pop();           
       }

       
    }
    
    int add(int val) {
        heap.push(val);
        if(heap.size()>size)  heap.pop(); 
        return heap.top();
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

参考:https://www.cnblogs.com/paulprayer/p/9855940.html

posted on 2019-03-18 20:43  kulukulu  阅读(246)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3