查看: 1000| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] PriorityQueue 顺序?

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 Musclekai 于 2020-9-18 14:53 编辑

按道理pq只能保证peek是最大/最小,其他都是无序。而且poll()完queue顺序会发生变化。
可是为什么下面这个解法的pq能一直保持poll的都是最大/最小值啊?lc621
  1. class Solution {
  2.     public int leastInterval(char[] tasks, int n) {
  3. int intervalCount = 0;
  4.     Map<Character, Integer> taskFrequencyMap = new HashMap<>();
  5.     for (char chr : tasks)
  6.       taskFrequencyMap.put(chr, taskFrequencyMap.getOrDefault(chr, 0) + 1);

  7.     PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<Map.Entry<Character, Integer>>(
  8.         (e1, e2) -> e2.getValue() - e1.getValue());

  9.     // add all tasks to the max heap
  10.     maxHeap.addAll(taskFrequencyMap.entrySet());

  11.     while (!maxHeap.isEmpty()) {
  12.       List<Map.Entry<Character, Integer>> waitList = new ArrayList<>();
  13.       int k = n + 1; // try to execute as many as 'k+1' tasks from the max-heap
  14.       for (; k > 0 && !maxHeap.isEmpty(); k--) {
  15.         intervalCount++;
  16.         Map.Entry<Character, Integer> currentEntry = maxHeap.poll();
  17.         if (currentEntry.getValue() > 1) {
  18.           currentEntry.setValue(currentEntry.getValue() - 1);
  19.           waitList.add(currentEntry);
  20.         }
  21.       }
  22.       maxHeap.addAll(waitList); // put all the waiting list back on the heap
  23.       if (!maxHeap.isEmpty())
  24.         intervalCount += k; // we'll be having 'n' idle intervals for the next iteration
  25.     }

  26.     return intervalCount;
  27.     }
  28. }
复制代码



上一篇:上完61b和cs170之后并不能帮助多少leetcode...
下一篇:分享一下5月份面试国内几家大公司的面试题,有找国内工作的同学可以参考下
全局:
pq其实就是heap,poll了一个出来之后,会调整heap让下一个依旧是最大/最小的啊
回复

使用道具 举报

🔗
Mr.Brain 2020-9-18 22:12:41 | 只看该作者
全局:
PQ是每次poll完之后的peak都还是最值,不是只有第一次
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表