zoukankan      html  css  js  c++  java
  • [LeetCode] Merge Intervals

    Given a collection of intervals, merge all overlapping intervals.

    Example 1:

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

    Example 2:

    Input: [[1,4],[4,5]]
    Output: [[1,5]]
    Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
    混合包含的区间
    思路:
    0. 需要将给定数组按照start的升序排序,当start相同时,按end升序排序。
    1. 需要混合的区间包含如下情况
      1. 如果start相同,若后一个元素的end大于前一个元素end,则融合
      2. 如果start不同,若后一个元素的end大于前一个元素end,则融合
    2. 不需要融合的情况
      1. 前一个元素end小于后一个元素的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:
        static bool cmp(const Interval& a, const Interval& b)
        {
            return a.start < b.start || (a.start == b.start && a.end < b.end);
        }
        vector<Interval> merge(vector<Interval>& intervals) {
            sort(intervals.begin(), intervals.end(), cmp);
            vector<Interval> res;
            for (int i = 0; i < intervals.size(); ++i)
            {
                if (i == 0 || intervals[i].start > res.back().end)
                    res.push_back(intervals[i]);
                else if (intervals[i].end > res.back().end)
                    res.back().end = intervals[i].end;
            }
            return res;
        }
    };
  • 相关阅读:
    7. Bagging & Random Forest
    VS 多工程代码编写
    C++(vs)多线程调试 (转)
    halcon发布
    windows 批处理文件调用exe
    Halcon编程-基于形状特征的模板匹配
    缺陷检测 深度学习
    PID控制
    去掉图片中的红色标记的方法?
    图像处理之图像拼接四
  • 原文地址:https://www.cnblogs.com/immjc/p/9066534.html
Copyright © 2011-2022 走看看