
import java.util.*;
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public ArrayList<Interval> merge(ArrayList<Interval> list) {
ArrayList<Interval> mergeList = new ArrayList<>();
Collections.sort(list, (a, b) -> a.start - b.start);
int len = list.size();
int i = 0;
while (i < len) {
int left = list.get(i).start;
int right = list.get(i).end;
while (i < len - 1 && list.get(i + 1).start <= right) {
right = Math.max(right, list.get(i + 1).end);
i++;
}
mergeList.add(new Interval(left, right));
i++;
}
return mergeList;
}
}
这是一个Java实现的解决方案,用于合并连续的时间区间。代码中定义了一个Interval类来表示时间区间,并提供了一个方法merge(),该方法接收一个Interval列表,通过排序和迭代,将相交的区间合并成新的区间列表。这个算法对于处理时间区间的数据整合问题非常有用。
998

被折叠的 条评论
为什么被折叠?



