/** * 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; } * } */class Solution { public Listmerge(List intervals) { List result = new ArrayList<>(); if (intervals == null || intervals.size() < 2) { return intervals; } Collections.sort(intervals, new Comparator (){ @Override public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }); Interval current = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { if (current.end >= intervals.get(i).start) { current.end = Math.max(current.end, intervals.get(i).end); } else { result.add(current); current = intervals.get(i); } } result.add(current); return result; }}
1. Has to be sorted if originally not sorted.
2. When merge end point, it could be totally covered instead of intersect.