码迷,mamicode.com
首页 > 其他好文 > 详细

56. Merge Intervals

时间:2018-10-19 20:50:02      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:The   pre   empty   over   amp   bsp   output   ret   ide   

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.

 

AC code:

/**
 * 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) {
        if (intervals.empty()) return {};
        vector<Interval> ans;
        sort(intervals.begin(), intervals.end(),
             [](const Interval& a, Interval& b) {
                 return a.start < b.start;
             });
        
        for (const auto& interval : intervals) {
            if (ans.empty() || interval.start > ans.back().end) {
                ans.push_back(interval);
            } else {
                ans.back().end = max(ans.back().end, interval.end);
            }
        }
        
        return ans;
    }
};

  

 

56. Merge Intervals

标签:The   pre   empty   over   amp   bsp   output   ret   ide   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9818599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!