• 【数据结构基础_数组】Leetcode 56.合并区间


    原题链接:Leetcode 56. Merge Intervals

    Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

    Example 1:

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

    Example 2:

    Input: intervals = [[1,4],[4,5]]
    Output: [[1,5]]
    Explanation: Intervals [1,4] and [4,5] are considered overlapping.
    
    • 1
    • 2
    • 3

    Constraints:

    • 1 <= intervals.length <= 104
    • intervals[i].length == 2
    • 0 <= starti <= endi <= 104

    方法一:排序

    思路:

    首先对所有区间按左节点升序排序
    然后遍历每个区间:

    • 当前节点的左节点处于上个区间中时,用当前节点的右节点更新上个区间的右节点
    • 否则说明当前区间和上个区间是不相交的,当前区间直接加入结果集

    C++代码:

    class Solution {
    public:
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            // 提前返回
            if (intervals.size() == 0) {
                return {};
            }
    
            // 按左端点升序排列
            sort(intervals.begin(), intervals.end());
            vector<vector<int>> ans;
    
            // 遍历每个区间
            for (int i = 0; i < intervals.size(); ++i) {
                // lr左右端点
                int l = intervals[i][0], r = intervals[i][1];
    
                // 分隔的区间 加入结果
                if (!ans.size() || ans.back()[1] < l) {
                    ans.push_back({l, r});
                }
                // 区间合并
                else {
                    ans.back()[1] = max(ans.back()[1], r);
                }
            }
            return ans;
        }
    };
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    复杂度分析:

    • 时间复杂度:O(nlogn),排序占了大头
    • 空间复杂度:O(logn),排序用掉的空间
  • 相关阅读:
    测评测试测试测试测从入门到精通
    dockerfile 快速部署jar项目运行
    ESP32_esp-idf_lvgl_V8环境搭建移植
    微服务生态系统:使用Spring Cloud构建分布式系统
    基础算法(三)#蓝桥杯
    [Lingo编程极速入门]——基础01
    Python之元组、字典和集合练习
    react-高阶组件
    python写好的程序打包成exe可执行文件
    GB/T28181协议介绍
  • 原文地址:https://blog.csdn.net/cwtnice/article/details/125995057