刷题进行到LeetCode 692.前K个高频单词
需要用到小根堆数据结构,发现自己对Java重写compare方法排序掌握很差,用了很长一段时间学习重写compare方法,同时现在并没有搞清楚 java实现Comparable接口和Comparator接口,并重写compareTo方法和compare方法 (感觉混在一起有点乱),这篇文章先仅仅学习重写compare方法进行排序。
仅仅用了ArrayList动态数组测试
ArrayList<Integer> al = new ArrayList<>();
al.add(2);
al.add(4);
al.add(1);
al.add(7);
al.add(5);
for (int n : al) System.out.print(n + " ");
System.out.println();
System.out.println("-----------------");
Collections.sort(al, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;// o1 - o2 升序,反之降序
}
});
for (int n : al) System.out.print(n + " ");
结果(o1 - o2):
2 4 1 7 5
-----------------
1 2 4 5 7
Process finished with exit code 0
(o2 - o1) :
2 4 1 7 5
-----------------
7 5 4 2 1
Process finished with exit code 0
后面再写那些混乱的一堆方法。