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 {
public:
    static bool compare(const Interval &a, const Interval &b)
    {
	    return a.start < b.start;
    }
    
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> result;
	    int size = intervals.size();
	    if (size < 1)
	    {
		    return result;
	    }

	    sort(intervals.begin(), intervals.end(), compare);
	    Interval temp(intervals[0].start, intervals[0].end);
	    for (int i = 1; i < size; i++)
	    {
		    if (temp.end >= intervals[i].start)
		    {
			    temp.end = max(temp.end, intervals[i].end);
		    }
		    else
		    {
			    result.push_back(temp);
			    temp.start = intervals[i].start;
			    temp.end = intervals[i].end;
		    }
	    }
	    result.push_back(temp);

	    return result;
    }
};


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