Leetcode每日一题:57. 插入区间

原题

给你一个 无重叠的按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

示例 1:

输入:intervals = [[1,3],[6,9]], newInterval = [2,5]
输出:[[1,5],[6,9]]

示例 2:

输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出:[[1,2],[3,10],[12,16]]
解释:这是因为新的区间 [4,8][3,5],[6,7],[8,10] 重叠。

示例 3:

输入:intervals = [], newInterval = [5,7]
输出:[[5,7]]

示例 4:

输入:intervals = [[1,5]], newInterval = [2,3]
输出:[[1,5]]

示例 5:

输入:intervals = [[1,5]], newInterval = [2,7]
输出:[[1,7]]

提示:

  • 0 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= intervals[i][0] <= intervals[i][1] <= 105
  • intervals 根据 intervals[i][0]升序 排列
  • newInterval.length == 2
  • 0 <= newInterval[0] <= newInterval[1] <= 105

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

解题思路 

考虑到intervals已经有序且无重叠,我们只需要依次取出interval,和待插入区间newInterval进行比较。根据interval和newInterval的相对位置和是否重叠,可以分成以下情况进行讨论:

1.如果interval在newInterval左侧且无重叠,那就插入interval,依次取出后面的interval进行比较。

2.如果interval在newInterval右侧且无重叠,那就先插入newInterval,再插入interval,后面直接插入剩余的interval。

3.如果interval和newInterval有重叠,那就合并interval和newInterval作为新的newInterval,依次取出后面的interval进行比较。

方便起见,我们要使用一个标志位记录newInterval是否被插入,如果intervals遍历结束,newInterval未被插入过,就要将其插入到最后。

完整实现如下:

class Solution {
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
         int left = newInterval[0];
        int right = newInterval[1];
        bool placed = false;
        vector<vector<int>> ans;
        for (const auto& interval: intervals) {
            if(interval[0] > right ){
                if(!placed){
                    ans.push_back({left,right});
                    placed=true;
                }
                ans.push_back(interval);
            }else if(interval[1] < left){
                ans.push_back(interval);
            }else{
                left = min(left,interval[0]);
                right = max(right,interval[1]);
            }
        }
        if(!placed){
            ans.push_back({left,right});
        }
        return ans;
    }
};

这里需要注意一点,我们在C++中常使用emplace_back优化插入性能。但是这里我们不能使用emplace_back,因为emplace_back(1,5)其实插入的是vector<int>(1,5),而不是vector<int>{1,5},前者是只有一个元素5的vector,后者是两个元素1和5的vector。

猜你喜欢

转载自blog.csdn.net/Mamong/article/details/132532484