[LeetCode]Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

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

思路:首先对元素进行排序,按照start升序排序。然后依次合并。

但是代码运行时间略长600ms。暂时没想到更好的解法。

LeetCode Source

代码如下:

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


你可能感兴趣的:([LeetCode]Merge Intervals)