自学内容网 自学内容网

【LeetCode热题100】【普通数组】合并区间

题目链接:56. 合并区间 - 力扣(LeetCode)

先排序,按左区排序,装第一个区间进入答案容器,判断答案容器钟最后一个区间的右区是否小于区间的左区,是则不能合并是新区间,否则可以合并

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>>ans;
        std::sort(intervals.begin(),intervals.end());
        for(auto&one:intervals){
            if(ans.empty()||ans.back()[1]<one[0]) // 空或者可以不能合并
                ans.push_back(one);
            else
                ans.back()[1]=max(ans.back()[1],one[1]); // 合并
        }
        return ans;
    }
};

原文地址:https://blog.csdn.net/weixin_62264287/article/details/137273225

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!