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

刚开始的时候想要一个一个比,每个都和后面的所有的比较merge,后来网上看到做法只要先按start time sort,然后遍历一遍即可,遇到merge的就merge。Notice the overriding of the compare method

/**
 * 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 ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval i1, Interval i2)
            {
                if (i1.start > i2.start)
                    return 1;
                else if (i1.start < i2.start)
                    return -1;
                return 0;
            }
        });
    
        for (int i = 0; i < intervals.size()-1; i++) {
            Interval curr = intervals.get(i);
            Interval next = intervals.get(i+1);
            if (next.start <= curr.end) {//merge
                Interval n = new Interval(curr.start, Math.max(curr.end, next.end));
                intervals.set(i, n);
                intervals.remove(i+1);
                i--;
            }
        }
        return intervals;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s