Merge Intervals

来源:互联网 发布:淘宝网天天特价女装套 编辑:程序博客网 时间:2024/06/03 20:37

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



(1)先将目标区间数组按X轴从小到大排序。例如:[2,3] [1,2] [3,9] ->[1,2] [2,3] [3,9]

(2)扫描排序后的目标区间数组,将这些区间合并成若干个互不相交的区间。例如 [2,3] [1,2] [4,9] ->[1,3] [4,9]

这里分三种情况:

a:[1,3] [2,6] -> [1,6] 第一个区间的end大于等于第二个区间的start,同时第二个区间的end大于第一个区间的end

b:[1,7] [2,4] -> [1,7] 第一个区间的end大于等于第二个区间的start,同时第二个区间的end小于第一个区间的end

c:[1,2] [3,4] -> [1,2] [3,4] 第一个区间的end小于第二个区间的start


//http://www.2cto.com/kf/201501/370271.html/** * 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 cmp(const Interval& a,const Interval&b)    {        return a.start<b.start;    }    vector<Interval> merge(vector<Interval>& intervals) {                vector<Interval> res;        int count = intervals.size();        if(count <= 1)            return intervals;        sort(intervals.begin(),intervals.end(),cmp);        res.push_back(intervals[0]);                for(int i = 1;i<count;i++)        {            Interval preIn = res.back();            Interval curIn = intervals[i];            if(curIn.start <= preIn.end && curIn.end > preIn.end)            {                preIn.end = curIn.end;                res.pop_back();                res.push_back(preIn);            }            else if(curIn.start > preIn.end)            {                res.push_back(curIn);            }        }                return res;            }};




0 0
原创粉丝点击