• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
xdubin
博客园    首页    新随笔    联系   管理    订阅  订阅
构建大小顶堆

  假设堆中存int类型的数据,直接一波PriorityQueue<Integer> queue = new PriorityQueue<>();即可完成小顶堆的构建,直接A了,因为默认的用new创建优先队列对象为小顶堆。

但是如何完成大顶堆的构建呢?

先介绍一种简洁的写法,利用lambda表达式来操作,PriorityQueue<Integer> queue = new PriorityQueue<>((x,y) -> y - x);即可A了。

还有一种写法如下所示:

static Comparator<Integer> cmp = new Comparator<Integer>() {
      public int compare(Integer e1, Integer e2) {   //注意e1和e2的顺序比较
        return e2 - e1;
      }
};

通过传入一个比较器,重新定义一下比较规则,再通过构造方法创建对象即可创建一个大顶堆。
PriorityQueue<Integer> queue = new PriorityQueue<>(cmp);

 Comparator<Object> cmp = new Comparator<Object>() {
   public int compare(Object o1, Object o2) {  //不同写法产生不同的比价方法
   //升序
   return o1-o2;
   //降序
   return o2-o1;
   }
 };

 

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