合并区间

题目链接:https://leetcode-cn.com/problems/merge-intervals/
题目描述:

题解:
排序:
1.按左边界排序,从左往右遍历,右值越大越好。
2.按右边界排序,从右往左遍历,左值越小越好。

class Solution {
public:
    static bool cmp(vector<int> &a, vector<int> &b)
    {
        return a[0] < b[0];
    }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> result;
        if(intervals.size() < 2)
            return intervals;
        sort(intervals.begin(), intervals.end(), cmp);  //按左边界排序
        result.push_back(intervals[0]);
        for(int i = 1; i < intervals.size(); i++)
        {
            if(result.back()[1] >= intervals[i][0])
            {
                result.back()[1] = max(result.back()[1], intervals[i][1]);  //更新边界值
            }else
            {
                result.push_back(intervals[i]);
            }
        }
        return result;

    }
};


class Solution {
public:
    static bool cmp(vector<int> &a, vector<int> &b)  //按右边界排序
    {
        return a[1] < b[1];
    }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if(intervals.size() < 2)
            return intervals;
        vector<vector<int>> result;
        sort(intervals.begin(), intervals.end(),cmp);
        result.push_back(intervals[intervals.size() - 1]);
        for(int i = intervals.size() - 2 ; i >= 0; i--)
        {
            if(result.back()[0] <= intervals[i][1])
            {
                result.back()[0] = min(result.back()[0], intervals[i][0]);
            }else
                result.push_back(intervals[i]);
        }
        return result;
    }
};

posted @ 2021-07-04 14:57  张宵  阅读(25)  评论(0编辑  收藏  举报