zoukankan      html  css  js  c++  java
  • Leetcode:56. Merge Intervals

    Description

    Given a collection of intervals, merge all overlapping intervals.

    Example

    For example,
    
    Given [1,3],[2,6],[8,10],[15,18],
    
    return [1,6],[8,10],[15,18].
    

    思路

    • 先按照start从小到大排序,然后遍历一遍,找出新的区间

    代码

    /**
     * Definition for an interval.
     * struct Interval {
     *     int start;
     *     int end;
     *     Interval() : start(0), end(0) {}
     *     Interval(int s, int e) : start(s), end(e) {}
     * };
     */
    class Solution {
    public:
        vector<Interval> merge(vector<Interval>& intervals) {
            vector<Interval> res;
            int len = intervals.size();
            if(len == 0) return res;
            
            sort(intervals.begin(), intervals.end(), 
                [](const Interval &a, const Interval &b){
                    if(a.start != b.start)
                        return a.start < b.start;
                    else return a.end < b.end;
                });
                
            int i = 0;
            while(i < len){
                Interval tmp;
                tmp.start = intervals[i].start;
                tmp.end = intervals[i].end;
                
                while(i + 1 < len && intervals[i + 1].start <= tmp.end){
                    tmp.end = max(tmp.end, intervals[i + 1].end);
                    i++;
                }
                
                res.push_back(tmp);
                i++;
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    moment.js相关知识总结
    git相关使用解释
    .我的第一篇博客
    QT项目配置
    重载->
    内核对象同步
    模式对话框与非模式对话框
    显示与隐式类型转换
    size_t与size_type
    系统级源代码:系统裁剪
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6875580.html
Copyright © 2011-2022 走看看