美文网首页
56. Merge Intervals/合并区间

56. Merge Intervals/合并区间

作者: 蜜糖_7474 | 来源:发表于2019-05-30 16:04 被阅读0次

    Given a collection of intervals, merge all overlapping intervals.

    Example 1:

    Input: [[1,3],[2,6],[8,10],[15,18]]
    Output: [[1,6],[8,10],[15,18]]
    Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

    Example 2:

    Input: [[1,4],[4,5]]
    Output: [[1,5]]
    Explanation: Intervals [1,4] and [4,5] are considered overlapping.

    NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

    AC代码

    bool cmp(const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; }
    
    class Solution {
    public:
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            sort(intervals.begin(), intervals.end(), cmp);
            vector<vector<int>> ans;
            for (auto interval : intervals) {
                if (ans.empty()) {
                    vector<int> t{interval[0], interval[1]};
                    ans.push_back(t);
                }
                else {
                    if (interval[0] <= ans[ans.size() - 1][1])
                        ans[ans.size() - 1][1] = max(ans[ans.size() - 1][1], interval[1]);
                    else {
                        vector<int> t{interval[0], interval[1]};
                        ans.push_back(t);
                    }
                }
            }
            return ans;
        }
    };
    

    总结

    将所有间隔按照左端点排序,逐一比较右端点,若下个组间隔的右端点小于上一组的,那么就有重叠,比较两个右端点,取其大者。没有重叠,就往结果vector<vector<int>>中添加新元素

    相关文章

      网友评论

          本文标题:56. Merge Intervals/合并区间

          本文链接:https://www.haomeiwen.com/subject/osevtctx.html