java的数据类型操作 - 堆


使用java做算法题时,与堆相关的常用操作:

大顶堆:

//其中map为全局变量

PriorityQueue pq = new PriorityQueue<>(new Comparator(
    public int comapre(Integer a, Integer b){
        return map.get(b) - map.get(a);
    }
));

小顶堆:

//其中map为全局变量
PriorityQueue pq = new PriorityQueue<>(new Comparator() {
            @Override
            public int compare(Integer a, Integer b) {
                return map.get(a) - map.get(b);
            }
        });
PriorityQueue pq = new PriorityQueue<>((x,y) -> (x.val - y.val));
PriorityQueue pq = new PriorityQueue<>((x,y) -> (x - y));