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来排序,然后依次合并相邻的重叠项。

代码:

/**
 * 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 comp(Interval a, Interval b)
    {
        return a.start<b.start;
    }
    vector<Interval> merge(vector<Interval> &intervals) {
        if(intervals.size()==0)
            return *(new vector<Interval>());
        
        sort(intervals.begin(),intervals.end(),comp);
        int cur = 0;
        while(cur<intervals.size()-1)
        {
            if(intervals[cur].end>=intervals[cur+1].start)
            {
                int s = intervals[cur].start;
                int e = intervals[cur].end>intervals[cur+1].end?intervals[cur].end:intervals[cur+1].end;
                intervals.erase(intervals.begin()+cur,intervals.begin()+cur+2);
                intervals.insert(intervals.begin()+cur,*(new Interval(s, e)));
            }
            else
            {
                cur++;
            }
        }
        return intervals;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17558309
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞