LeetCode 56 - Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

/**
 * 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 List<Interval> merge(List<Interval> intervals) {
    if(intervals == null || intervals.size() <= 1) {
        return intervals;
    }
    Collections.sort(intervals, new Comparator<Interval>(){
        public int compare(Interval o1, Interval o2) {
            return o1.start - o2.start;
        }
    });
    List<Interval> result = new ArrayList<>();
    Interval prev = intervals.get(0);
    for(int i=1; i<intervals.size(); i++) {
        Interval interval = intervals.get(i);
        if(prev.end >= interval.start) {
            Interval merged = new Interval(prev.start,Math.max(prev.end,interval.end));
            prev = merged;
        } else {
            result.add(prev);
            prev = interval;
        }
    }
    result.add(prev);
    return result;
}

 

你可能感兴趣的:(LeetCode 56 - Merge Intervals)