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.
 * 1
 */
struct cmp{
    bool operator()(const Interval & interval1, const Interval & interval2){
        return interval1.start < interval2.start;
    }
}mycmp;

class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> res;
        sort(intervals.begin(), intervals.end(), mycmp);

        int n = intervals.size();
        if(n > 0){
            for(int i = 0; i < n; i++){
                int s = intervals[i].start;
                int e = intervals[i].end;

                while((i +1  < n) && intervals[i + 1].start <= e){
                    //注意此处要不断更新区间中点的位置
                    e = max(e, intervals[i + 1].end);
                    i++;
                }
                Interval tmp(s, e);
                res.push_back(tmp);
            }
        }
        return res;
    }
};

results matching ""

    No results matching ""