Comparator.thenComparing
Comparator.thenComparing方法是在Java 8中引入的。
对于int、long和double数据类型的排序键,比较器分别有thenComparingInt、thenComparingLong和thenComparingDouble默认方法。
Comparator接口中的thenComparing默认方法如下,
default Comparator<T> thenComparing(Comparator<? super T> other) {
Objects.requireNonNull(other);
return (Comparator<T> & Serializable) (c1, c2) -> {
int res = compare(c1, c2);
return (res != 0) ? res : other.compare(c1, c2);
};
}
LeetCode 56.合并区间
题目
以数组 intervals
表示若干个区间的集合,其中单个区间为 intervals[i]
= [starti
, endi
] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
示例1
【输入】intervals = [[1,3],[2,6],[8,10],[15,18]]
【输出】[[1,6],[8,10],[15,18]]
【解释】区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例2
【输入】intervals = [[1,4],[4,5]]
【输出】[[1,5]]
【解释】区间 [1,4] 和 [4,5] 可被视为重叠区间。
约束
1 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= starti <= endi <= 10^4
题解
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* leetcode 56.合并区间
*/
public class MergeInterval {
public static void main(String[] args) {
int[][] intervals = new int[][]{{1, 3}, {2, 6}, {8, 10}, {5, 6}, {2, 5}, {15, 18}};
int[][] res = merge(intervals);
System.out.println(JsonUtils.toJson(res));
}
private static int[][] merge(int[][] intervals) {
if (intervals.length <= 1 || intervals[0].length <= 1) {
return intervals;
}
// 数组排序 先按区间[start, end]中start排序,再按end排序
Arrays.sort(intervals, ((Comparator<int[]>) (o1, o2) -> o1[0] - o2[0]).thenComparing(Comparator.comparingInt(o -> o[1])));
int start = intervals[0][0];
int end = intervals[0][1];
List<int[]> res = new ArrayList<>();
for (int i = 1; i < intervals.length; i++) {
int curStart = intervals[i][0];
int curEnd = intervals[i][1];
if (curStart > end) {
res.add(new int[]{start, end});
start = curStart;
end = curEnd;
} else {
end = curEnd;
}
}
res.add(new int[]{start, end});
return res.toArray(new int[res.size()][]);
}
}
参考链接
1、javase/docs/Comparator
2、concretepage/java-8/comparator-thencomparing