一、给二维数组排序
按照元素的第一维来排序:
只能给对象添加比较器,无法给基础类型添加比较器,数组也是一种对象。
int[][] trips = new int[m][n];
//二维数组的初始化操作
Arrays.sort(trips, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0]-o2[0];
}
});
二、使用优先队列(为存储对象编写比较器)
Queue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0]-o2[0];
}
});
三、使用优先队列(为Map.Entry<>条目编写比较器)
HashMap<Character,Integer> map = new HashMap<>();
//...
PriorityQueue pq = new PriorityQueue(new Comparator<Map.Entry<Character,Integer>>(){
public int compare(Map.Entry<Character,Integer> o1,Map.Entry<Character,Integer> o2){
return o2.getValue()-o1.getValue();
}
});
pq.addAll(map.entrySet());
四、简单数学基础
- 看到加法到想到求余
- 数字N若是奇数,则它的约数必然都是奇数;若为偶数,则它的约数可奇可偶。