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].

Solution

/**
 * 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 List<Interval> merge(List<Interval> intervals) {
        if(intervals == null || intervals.size() == 0) return new ArrayList<Interval>();
        Collections.sort(intervals, (a,b) -> Integer.compare(a.start, b.start));
        List<Interval> ans = new ArrayList<Interval>();
        Interval inter = null;
        for(Interval i: intervals) {
            if(inter == null) {
                inter = i;
            } else {
                if(inter.end >= i.start) {
                    inter.end = Integer.max(inter.end, i.end);
                } else {
                    ans.add(inter);
                    inter = i;
                }
            }
        }
        ans.add(inter);
        return ans;
    }
}

results matching ""

    No results matching ""