思路:先排序,后合并
个人认为这种方法还是比较简单的,只考虑三种情况
public static void main(String[] args) {
// 输入: [[1,3],[2,6],[9,13],[7,8],[20,25]]
// 输出: [[1,6], [7,8], [9,13], [20,25]]
// 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
//梳理逻辑,分为这三种情况
//[1,3] [2,3]
//[1,3] [2,4]
//[1,3] [4,5]
//传入参数
List<Interval> intervals = new ArrayList<>();
Interval interval1 = new Interval(1,3);
Interval interval2 = new Interval(2,6);
Interval interval3 = new Interval(9,13);
Interval interval4 = new Interval(7,8);
Interval interval5 = new Interval(20,25);
intervals.add(interval1);
intervals.add(interval3);
intervals.add(interval2);
intervals.add(interval4);
intervals.add(interval5);
System.out.println(intervals);
//先排序
List<Interval> intervalsSort = mergeSort(intervals);
System.out.println(intervalsSort);
//再合并
List<Interval> merge = mergeNew(intervalsSort);
System.out.println(merge);
}
public static List<Interval> mergeSort(List<Interval> intervals) {
//排序方法一
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
Integer start1 = o1.start;
Integer start2 = o2.start;
return start1.compareTo(start2);
}
});
//排序方法二
// intervals.sort((o1,o2)->{
// Integer start1 = o1.start;
// Integer start2 = o2.start;
// return start1.compareTo(start2);
// });
return intervals;
}
public static List<Interval> mergeNew(List<Interval> intervals) {
for (int i = 0; i < intervals.size(); i++) {
Interval temp1 = intervals.get(i);
for (int j = i+1; j < intervals.size(); j++) {
Interval temp2 = intervals.get(j);
if (temp1.start <= temp2.start && temp1.end >= temp2.end){
intervals.remove(j);
}else if (temp1.start <= temp2.start && temp1.end <= temp2.end && temp1.end >= temp2.start){
temp1.end = temp2.end;
intervals.remove(j);
}
intervals.set(i,temp1);
}
}
return intervals;
}
内部类
static class Interval {
int start, end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "["+start+","+end+"]";
}
}
老哥,留个赞再走