题解 | #合并区间#

合并区间

https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */

#include <vector>
class Solution {
public:
     //定义排序规则,按照区间的左端点排序
    //  static bool cmp(const Interval &a,const Interval &b){
    //     return (a.start<b.start); 
    // }
    vector<Interval> merge(vector<Interval> &intervals) {
        sort(intervals.begin(), intervals.end(),[&](Interval & a, Interval & b){
            return a.start < b.start;
        });
        vector<Interval> res;
        int st = -1, end = -1;
        for(auto num : intervals){
            if(end < num.start){
                if(st != -1) res.push_back(Interval(st, end));
                st = num.start, end = num.end;
            } else {
                end = max(num.end, end);
            }
        }
        if(st != -1)
            res.push_back(Interval(st,end)); 
        return res;
    }
};

全部评论

相关推荐

04-06 16:59
已编辑
河南工业大学 Java
牛牛牛的牛子:最好扔了,实在没有选择的选择
点赞 评论 收藏
分享
03-09 20:32
运营
牛客972656413号:成绩管理系统会不会有点太。。。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务