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

#Leetcode# 56. Merge Intervals

时间:2018-11-25 20:18:17      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:public   size   blank   ati   input   sort   http   好玩的   ack   

https://leetcode.com/problems/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 considered overlapping.

代码:

/**
 * 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 {};
        sort(intervals.begin(), intervals.end(), [](Interval &a, Interval &b) {return a.start < b.start;});
        vector<Interval> ans{intervals[0]};
        for (int i = 1; i < intervals.size(); ++i) {
            if (ans.back().end < intervals[i].start) {
                ans.push_back(intervals[i]);
            } else {
                ans.back().end = max(ans.back().end, intervals[i].end);
            }
        }   
        return ans;
    }
};

  那个 $sort$ 排序没见过 看了题解会写的 记上一笔!!!!总是会看到很多没见过的有点好玩的东西 emmmm 还不是自己太菜了 o(╥﹏╥)o

#Leetcode# 56. Merge Intervals

标签:public   size   blank   ati   input   sort   http   好玩的   ack   

原文地址:https://www.cnblogs.com/zlrrrr/p/10016136.html

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