讨论/《数组和字符串》 - 合并区间/
《数组和字符串》 - 合并区间

关键是排序:左端再右端
C++

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        sort(intervals.begin(),intervals.end(),[](const auto& a, const auto& b){
            return a[0]<b[0] || (a[0]==b[0] && a[1]<b[1]);
        });

        vector<vector<int> > final;
        vector<int> element;

        vector<vector<int> >::iterator iter=intervals.begin();
        int left=(*iter)[0];
        int right=(*iter)[1];
        iter++;

        while(iter!=intervals.end()){
            if((*iter)[0]>right){
                element.push_back(left);
                element.push_back(right);
                final.push_back(element);
                element.clear();
                left=(*iter)[0];
                right=(*iter)[1];
            }else{
                if((*iter)[1]>right){
                    right=(*iter)[1];
                }
            }
            iter++;
        }

        element.push_back(left);
        element.push_back(right);
        final.push_back(element);

        return final;
    }
};
展开全部 27 讨论