leetcode 56. 合并区间

题目描述

代码:

cpp 复制代码
class Solution {
    struct Interval{
        int left;
        int right;
        Interval(int l=0,int r=0):left(l),right(r){}
        bool operator<(const Interval& rhs) const{
            return left<rhs.left;
        }
    };

public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int len = intervals.size();
        vector<Interval> myIntervals(len);
        for(int i = 0;i <len;i++){
            myIntervals[i].left =intervals[i][0];
            myIntervals[i].right=intervals[i][1];
        }
        sort(myIntervals.begin(),myIntervals.end());
        vector<vector<int>> res;
        vector<int> range(2,0);
        int low = 0;
        int high = 0;
        for(int i = 1;i < len;i++){
            if(myIntervals[high].right >= myIntervals[i].right)
                continue;

            if(myIntervals[high].right >= myIntervals[i].left){
                high = i;
            }else{
                range[0] = myIntervals[low].left;
                range[1] = myIntervals[high].right;
                res.push_back(range);
                low = i;
                high = low;
            }
        }
        range[0] = myIntervals[low].left;
        range[1] = myIntervals[high].right;
        res.emplace_back(range);
        return res;
    }
};
相关推荐
alphaTao13 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习13 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
不知名XL14 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––14 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao15 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
TracyCoder12316 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
望舒51318 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
铉铉这波能秀18 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.18 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
铉铉这波能秀19 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple