当前位置:网站首页>Niuke.com: consolidation interval

Niuke.com: consolidation interval

2022-06-22 19:03:00 lsgoose

Let's deal with it normally in sequence :

First of all, in accordance with the start Sort the array from small to large , Then we maintain an array sequence of answers .

For each intervals:

If the current interval is start Than the last interval in the answer sequence end Small or equal to , We update the last interval end Original end And the new interval end The maximum of

otherwise , Add a new range to the answer

The code is as follows :

/**
 * 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 cmp(Interval &a, Interval &b){
        return a.start < b.start;
    }
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> res;
        if(intervals.size()==0) return res;
        sort(intervals.begin(), intervals.end(), cmp);
        res.push_back(intervals[0]);
        for(int i=1;i<intervals.size();++i){
            if(intervals[i].start <= res.back().end){
                res.back().end=max(res.back().end, intervals[i].end);
            }else{
                res.push_back(intervals[i]);
            }
        }
        return res;
    }
};

原网站

版权声明
本文为[lsgoose]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221729500897.html