1、
Given a collection of intervals, merge all overlapping intervals.
[ [ [1, 3], [1, 6], [2, 6], => [8, 10], [8, 10], [15, 18] [15, 18] ] ]
2、思路
1、对所有的集合排个序,按小到大
2、迭代判断,从第一个判断,如果第二个的start 小于第一个的end,end重新判断
3、如果大于,间断,添加到集合里面
4、最后,添加进集合。
3、代码
public class MergeIntervals { public ArrayList<Interval> merge(ArrayList<Interval> intervals) { if (intervals == null || intervals.size() <= 1) { return intervals; } //排序 Collections.sort(intervals, new IntervalComparator()); ArrayList<Interval> result = new ArrayList<Interval>(); Interval last = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { Interval curt = intervals.get(i); //区间判断 if (curt.start <= last.end) { last.end = Math.max(last.end, curt.end); } else { result.add(last); last = curt; } } result.add(last); return result; } private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } } } class Interval { int start, end; Interval(int start, int end) { this.start = start; this.end = end; } }