Saturday, May 9, 2015

[LeetCode] 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.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
    static bool compare(Interval & i1, Interval & i2)
    {
        return i1.start < i2.start;
    }
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), compare);
        int len = intervals.size();
        vector<Interval> res;
        if(0 == len) return res;
        res.push_back(intervals[0]);
        for(int i=1;i<len;i++)
        {
            Interval & cur = res[res.size()-1];
            if(cur.end >= intervals[i].start)
            {
                cur.end = max(cur.end, intervals[i].end);
            }
            else
            {
                res.push_back(intervals[i]);
            }
        }
        return res;
    }
};