定义比较器

本文主要是自定义比较器 以用来sort或者定义任意想要比较的东西。

只有我们想sort什么东西的时候 才会想到定义比较器
一般来说 使用Comparator有三种情况:
Arrays.sort(nums, new Comparator<int []>(){public int compare(){}}) //when we want to sort an array but the element is not primitive
Collections.sort() //when we want to sort some other data structures
new DataStructureConstructor(, lambda expression Comparator) //many data structures’s constrctors contains this kind of thing
一般来说 想implement Comparable,一般是针对类来说的 如果我们想自己定义某个类 而且后面也用到之间的比较,我们就要让这个类implement Comparable,然后override compareTo() 这个方法
LC56
这是之前题目没有改过时答案定义的比较器

Collections.sort(intervals, (a, b) -> a.start - b.start);

LC23

PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val)

how to sort a n-dimension array with first column as its comparator
???
LC472
sort an array according to its length

Arrays.sort(words, (a, b) -> (a.length() - b.length()));
Arrays.sort(people, new Comparator<int []>() {
    @Override
    public int compare(int[] a, int[] b) {
      //大的在前面,也就是说b[0] - a[0]可以保证
      //第一个元素大的在前面
        if(a[0] != b[0]) return -a[0]+b[0];
        //这个就保证了第二个元素小的在前面
        else return a[1]-b[1];
    }
});

Comparator<int[]> comparator = new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return 0;
    }
};

LC642
we have a self define class called Node:

class Node {
        String sentence;
        int times; //instead of using isWord, we use times as its attribute
        
        public Node(String st, int t) {
            sentence = st;
            times = t;
        }
    }

Node have two attributes. and we want to compare times first, and if times is the same for two instance of node, we compare the sentence based on the Lexicographic order. so:

Collections.sort(list, (a, b) -> a.times == b.times? a.sentence.compareTo(b.sentence): b.times - a.times); //bigger times first, small lexicograpgic ahead

and if you want have a hashmap: HashMap<String, List<String>> map, and you would love to solve all value in lexicographic order, then:

map.forEach((key, value) -> Collections.sort(value)); 
posted @ 2020-04-26 23:14  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报