如果比较器使用其他变量,比较器何时消耗变量?

如何解决如果比较器使用其他变量,比较器何时消耗变量?

下面有一个代码示例,基本上,我想获取input

中值从低到高的数组的索引

它可以按预期工作,但是当我开始添加一些逻辑来更改input的值时,poll()方法并不总是返回正确的索引。

但是我不知道这是怎么发生的

    public static void main(String[] args) {
        Solution s = new Solution();
        int[][] input = new int[][]{
                {8,6,8,1,4,1},{10,3,9,10},{1,5,5},7,3},{6,{3,10,10}
        };
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> input[o[0]][o[1]]));
        for(int i = 0; i < input.length; i++) {
            for (int j = 0; j < input[0].length; j++) {
                pq.add(new int[]{i,j});
            }
        }
        while(!pq.isEmpty()) {
            int[] h = pq.poll();
            // if I add something to change the input,the poll() method not always returns the index of min val,why?
            System.out.println(h[0] + "  " + h[1] + "  " + input[h[0]][h[1]]);
        }
    }

解决方法

在添加之后和从PriorityQueue中删除之后,将调用比较器。进行比较以对支持队列的最小堆进行排序。

更具体地说,添加后将调用PriorityQueue#siftUp,删除时将调用PriorityQueue#siftDown,但仅在删除队列的第0个元素之后才调用。这两种方法都使用比较器。

考虑以下简单示例:

public static void main(String[] args) {
  
  int[] a = {1};
  int[] b = {2};
  int[] c = {3};
  int[] d = {4};

  int[][] input = new int[][] {a,b,c,d};
  PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));

  pq.addAll(Arrays.asList(input));

  d[0] = -1;

  while (!pq.isEmpty()) {
    int[] h = pq.poll();
    System.out.println(Arrays.toString(h));
  }
}

最初,当添加a,b,c,d时,该队列从筛选操作中部分排序,因此至少可以保证队列的头为{1}。然后将元素d更改为-1。

不用说,在变异过程中没有调用比较器。

在循环内部,当您第一次 调用民意测验时,您将删除head元素a = 1,并且在之后将队列重新排序使用比较器删除堆头。

下一个要删除的元素是d = -1。因此,在我的简化示例中,删除的打印顺序为1,-1,2,3,这表明比较器在添加到队列后被调用,在之后从队列中被删除,仅此而已。

我将重点放在之后一词,因为如果在将其从队列中删除之前调用过该词,则在上面的示例中我们会得到不同的结果(-1、1、2、3而不是1,-1,3)

不用说,我在这里给出的示例是一个很好的理由,为什么您不应该在添加PriorityQueue后更改它们。

,

总而言之,您基本上是在创建一个指向可变整数的“地址”(元组)排序队列。

在队列方法期间将插入一个“地址”(元组),但此后不会插入。 如果更改了引用的整数,则什么都没有告诉已排序的集合重新排序。您正在有效地破坏集合,因为优先级队列的内部会感到混乱,因为通常希望状态被排序以便插入适当的位置。

PQ使用'siftup / siftdown',基本上使项目向上或向下起泡。如果由于后门突变而不再对队列进行排序,则筛选将过早结束,并使集合损坏。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-