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

56. Merge Intervals

时间:2018-05-19 14:44:52      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:init   struct   als   return   max   def   script   leetcode   ems   

https://leetcode.com/problems/merge-intervals/description/

/**
 * 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) {
        auto comp = [](const Interval& i1, const Interval& i2) {
            return i1.start < i2.start || i1.start == i2.start && i1.end < i2.end;
        };
        sort(intervals.begin(), intervals.end(), comp);
        
        vector<Interval> res;
        if (intervals.empty())  return res;
        Interval cur = intervals[0];
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i].start <= cur.end) {
                cur.end = max(cur.end, intervals[i].end);
            }
            else {
                res.push_back(cur);
                cur = intervals[i];
            }
        }
        res.push_back(cur);
        return res;
    }
};

 

56. Merge Intervals

标签:init   struct   als   return   max   def   script   leetcode   ems   

原文地址:https://www.cnblogs.com/JTechRoad/p/9060127.html

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