56. Merge Intervals**

56. Merge Intervals**

https://leetcode.com/problems/merge-intervals/description/

题目描述

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.

解题思路

给定一些区间, 将有重合部分的区间合并.

思路 1: 假设区间为 [a, b], 那么可以按照 b 的大小进行区间的从小到大排序, 然后再进行合并.

思路 2: 假设区间为 [a, b], 那么可以按照 a 的大小进行区间的从小到大排序, 然后再进行合并.

C++ 实现 1

思路 1. 从后向前进行处理.

class Solution {
private:
    struct Comp {
        bool operator()(const vector<int> &p, const vector<int> &q) {
            return p[1] < q[1];
        }  
    };
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if (intervals.empty()) return {};
        std::sort(intervals.begin(), intervals.end(), Comp());
        // 初始化先加入 .back()
        vector<vector<int>> res{intervals.back()};
        for (int i = intervals.size() - 2; i >= 0; --i) {
            auto prev = res.back();
            auto current = intervals[i];
            if (prev[0] > current[1])
                res.push_back(current);
            else
                res.back()[0] = std::min(prev[0], current[0]);
        }
        return res;
    }
};

C++ 实现 2

思路 2. 从前向后进行处理.

class Solution {
private:
    struct Comp {
        bool operator()(const vector<int> &p, const vector<int> &q) {
            return p[0] < q[0];
        }  
    };
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if (intervals.empty()) return {};
        std::sort(intervals.begin(), intervals.end(), Comp());
        // 初始化为 .front()
        vector<vector<int>> res{intervals.front()};
        for (int i = 1; i < intervals.size(); ++i) {
            auto prev = res.back();
            auto current = intervals[i];
            if (prev[1] < current[0])
                res.push_back(current);
            else
                res.back()[1] = std::max(prev[1], current[1]);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值