/* * 56. Merge Intervals * 2016-5-7 by Mingyang * 直接比较就好了,不要分的太细 * 开始想分三类,一类是加prev,一类是merge,另一类是prev包含了cur * 现在简化了,2,3合在一起了,都merge * 另外就是注意如何写comparator */
public List<Interval> merge(List<Interval> intervals) { if (intervals == null || intervals.size() <= 1) return intervals; Collections.sort(intervals, new Comparator<Interval>(){ public int compare(Interval i1, Interval i2) { return i1.start - i2.start; } }); List<Interval> result = new ArrayList<Interval>(); Interval prev = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { Interval curr = intervals.get(i); if (prev.end >= curr.start) { // merged case Interval merged = new Interval(prev.start, Math.max(prev.end, curr.end)); prev = merged; } else { result.add(prev); prev = curr; } } result.add(prev); return result; }