比较器
继承Comparator<>接口,重写里面的compareTo方法。
public static class IdAscendingComparator implements Comparator<Strudent>{
@Override
public int compare(Student o1, Student o2){
return o1.id - o2.id;
}
}
是系统提供的很好的排序方法,可以直接调用。
然后用Arrays.sort调用比较器
Arrays.sort(students, new AgeDescendingComparator());
系统提供的方法可以使用比较器
优先级队列的实际物理结构就是堆
PriorityQueue<泛型> heap = new PriorityQueue<>(比较器)
如
PriorityQueue heap = new PriorityQueue<>(new IdAscendingComparator())
红黑树TreeSet<>也可以使用比较器
比较器的作用是,当问题的重点不是放在排序上面,而是排序后的业务逻辑,可以直接用比较器,不然写一坨排序代码在那里没必要
桶排序、计数排序、基数排序的介绍
1,非基于比较的排序,与被排序的样本的实际数据状况很有关系,所 以实际中并不经常使用
2,时间复杂度O(N),额外空间复杂度O(N)
3,稳定的排序
补充问题 给定一个数组,求如果排序之后,相邻两数的最大差值,要求时 间复杂度O(N),且要求不能用非基于比较的排序。
代码
public class Code_11_MaxGap {
public static int maxGap(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int len = nums.length;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);//找出数组最小值最大值
}
if (min == max) {
return 0;
}
boolean[] hasNum = new boolean[len + 1];
int[] maxs = new int[len + 1];
int[] mins = new int[len + 1];
int bid = 0;
for (int i = 0; i < len; i++) {
bid = bucket(nums[i], len, min, max);
mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums[i];
maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums[i];
hasNum[bid] = true;
}
int res = 0;
int lastMax = maxs[0];
int i = 1;
for (; i <= len; i++) {
if (hasNum[i]) {
res = Math.max(res, mins[i] - lastMax);//全局最大差值
lastMax = maxs[i];
}
}
return res;
}
public static int bucket(long num, long len, long min, long max) {
return (int) ((num - min) * len / (max - min));
}