PriorityQueue-最大堆/Comparator比较的写法(溢出问题)


今天利用PriorityQueue实现最大堆,写了一个bug。

原始写法:

        Queue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });

用lambda简化后:

Queue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1);

注意到,这里o2-o1是会产生溢出的,会导致结果不正确。

所以采用这种写法更好:

        Queue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });

用lambda简化后:

Queue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2.compareTo(o1));

Queue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder());


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM