力扣_数组21—合并区间

题目

合并区间

输入: i n t e r v a l s = [ [ 1 , 3 ] , [ 2 , 6 ] , [ 8 , 10 ] , [ 15 , 18 ] ] intervals = [[1,3],[2,6],[8,10],[15,18]] intervals=[[1,3],[2,6],[8,10],[15,18]]
输出: [ [ 1 , 6 ] , [ 8 , 10 ] , [ 15 , 18 ] ] [[1,6],[8,10],[15,18]] [[1,6],[8,10],[15,18]]
解释:区间 [ 1 , 3 ] [1,3] [1,3] [ 2 , 6 ] [2,6] [2,6] 重叠, 将它们合并为 [ 1 , 6 ] [1,6] [1,6].

思路

比就行了

代码

class Solution {
public:
    // static bool cmp(vector x, vector y){
    //     return x[0]
    // }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int n = intervals.size();
        if(n == 1)
            return intervals;
        sort(intervals.begin(), intervals.end());
        // return intervals;
        int flag = 0;
        int l=intervals[0][0], r=intervals[0][1];
        vector<vector<int>> ret;
        for(int i = 1; i < n; i++){
            if(intervals[i][0]-r > 0){
                ret.push_back({l, r});
                l = intervals[i][0];
                r = intervals[i][1];
                flag = 0;
            }
            // if(intervals[i][0]-intervals[i-1][1] <= 0 && intervals[i][1]-intervals[i-1][1] > 0){
            if(intervals[i][0]-r <= 0 && intervals[i][1]-r > 0){
                flag = 1;
                r = intervals[i][1];
            }
        }
        ret.push_back({l, r});
        return ret;
    }
};

你可能感兴趣的:(算法,leetcode,职场和发展)