其他分享
首页 > 其他分享> > LeetCode56. Merge Intervals

LeetCode56. Merge Intervals

作者:互联网

题意

给n个区间, 将重叠的区间进行合并

解法

排序

代码

vector<vector<int>> merge(vector<vector<int>>& intervals) {
    int N = intervals.size();
    if (N == 0) return {};

    sort(intervals.begin(), intervals.end());
    vector<vector<int>> ans;
    ans.push_back(intervals[0]);
    for (int i = 1; i < N; i++) {
        int n = ans.size();
        vector<int> intv = intervals[i];
        int L = intv[0], R = intv[1];
        int l = ans[n-1][0], r = ans[n-1][1];
        
        if (L <= r) {
            ans[n-1][0] = l;
            ans[n-1][1] = max(R, r);
        }
        else {
            ans.push_back(intv);
        }
    }

    return ans;
}

标签:LeetCode56,vector,Intervals,int,Merge,intervals,ans,intv,size
来源: https://www.cnblogs.com/Figure_at_a_Window/p/16394776.html