6/13/2014

120. Merge Intervals

/**
 * 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) {
        ArrayList<Interval> res = new ArrayList<Interval> ();
       
        if (intervals.size()==0) return res;
       
        //sort by start
        Collections.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval o1, Interval o2) {
                return o1.start-o2.start;
            }
        });
       
        Interval ref = intervals.get(0);
       
        for (int i=1; i<intervals.size(); i++) {
            Interval cur = intervals.get(i);
            if (cur.end<ref.start) res.add(cur);
            else if (cur.start>ref.end) {
                res.add(ref);
                ref = cur;
            } else ref = new Interval(Math.min(ref.start, cur.start), Math.max(ref.end, cur.end));
        }
        res.add(ref);
       
        return res;
    }
}

没有评论:

发表评论