PriorityQueue用法

PriorityQueue优先队列

PriorityQueue<Integer> queue=new PriorityQueue<>(); //默认从小到大
PriorityQueue<Integer> queue=new PriorityQueue<>( (a,b)->(b-a)); //从大到小
PriorityQueue<int[]> queue=new PriorityQueue<>((a,b)->(a[0]-b[0])); //自定义排序 数组的第一个数字

自定义排序

第一种写法:

类不实现Comparable接口,

lamda表达式定义compator

PriorityQueue<Eage> queue=new PriorityQueue<>(               
                (a,b)->(a.weight-b.weight>0?-1:1) //lamda表达式,compartor如果顺序对返回1,如果顺序不对返回-1
            );
class Eage{
    int node;
    double weight;
    Eage(int x,double y){
        this.node=x;
        this.weight=y;
    }
}

第二种写法:

类不实现Comparable接口,

自定义新的compator

PriorityQueue<Eage> queue=new PriorityQueue<>(
    new Comparator<Eage>() {
        @Override
        public int compare(Eage o1, Eage o2) {
            return o1.weight-o2.weight>0?-1:1;
        }
    }
);
class Eage{
    int node;
    double weight;
    Eage(int x,double y){
        this.node=x;
        this.weight=y;
    }
}

第三种写法:

类实现Comparable接口

优先队列可以不定义compator

PriorityQueue<Eage> queue=new PriorityQueue<>();
class Eage implements Comparable<Eage>{
    int start;
    int end;
    double weight;
    public Eage(int x,int y,double z){
        this.start=x;
        this.end=y;
        this.weight=z;
    }

    public int compareTo(Eage eage){
        return this.weight-eage.weight>0?-1:1;
    }
}

posted on 2022-01-18 15:24  阿ming  阅读(220)  评论(0编辑  收藏  举报

导航