Leetcode 56 Merge Intervals

2018-01-12 15:03:50 浏览数 (1)

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].

重叠区间合并,

排序后检查当前区间右边和下一个区间左边是否交叉,交叉则合并

代码语言:javascript复制
/**
 * 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 cmp(const struct Interval &a,const struct Interval &b)
    {
        if(a.start!=b.start)
            return a.start<b.start;
        return a.end<b.end;
    }
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<int> test;
        sort(intervals.begin(),intervals.end(),cmp);//注意这里的cmp写在类内,需要是static的
        vector<Interval> result;
        for(int i=0;i<intervals.size();)
        {
            Interval temp=intervals[i];
            i  ;
            while(i<intervals.size() && temp.end>=intervals[i].start)
                temp.end=max(temp.end,intervals[i  ].end);
            result.push_back(temp);
        }
        return result;
    }
};

0 人点赞