C++速通LeetCode中等第9题-合并区间

排序后迭代,遇到符合条件的就删除前一项,合并到后一项。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int left = 0,right = 0;
        sort(intervals.begin(), intervals.end());
        vector<int> tmp;
        for(auto it = intervals.begin(); it != --(intervals.end()); )
        {
            if((*it)[1] >= (*(++it))[0])
            {
                left = (*(--it))[0];
                right = (*it)[1];
                it = intervals.erase(it);
                right = max(right,(*it)[1]);
                tmp.push_back(left);
                tmp.push_back(right);
                *(it) = tmp;
                tmp.clear();
            }
        }
        return intervals;
    }
};
相关推荐
Lion Long1 小时前
在 Windows 上快速搭建 VSCode 的 C++ 开发环境(基于 WSL)
linux·c++·windows·vscode·wsl
idontknow2331 小时前
从零开始编写 webserver (三) 线程池与数据库连接池
c++
雪花desu1 小时前
【Hot100-Java中等】:字母异位词分组
java·算法·leetcode·哈希表
秋邱1 小时前
Java抽象类与接口的核心区别:定义、特性与选型逻辑全解析
java·开发语言
Word码1 小时前
LeetCode283. 移动零(双指针精讲)
算法·leetcode·职场和发展
ly_Enhs1 小时前
Vulkan 一句话心智词典(去恐惧版)
开发语言·vulkan图形渲染c/c++
成为大佬先秃头1 小时前
渐进式JavaScript框架:Vue 工具 & 模块化 & 迁移
开发语言·javascript·vue.js
程序员小白条1 小时前
提前实习的好处有哪些?有坏处吗?
java·开发语言·数据结构·数据库·链表
ss2731 小时前
Executors预定义线程池-正确使用姿势
linux·开发语言·python
七夜zippoe1 小时前
Python高级数据结构深度解析:从collections模块到内存优化实战
开发语言·数据结构·python·collections·内存视图