先给Intervals数组按start从小到大开始排序,然后,每次判断右边的Intervals.start是否小于前面所有的Interval.end即前面Intervals.end的最大值,是则还在同一个区间内,否则不在同一区间内
class Solution { public: static bool cmp(struct Interval a,struct Interval b){ return a.start<b.start; } vector<Interval> merge(vector<Interval> &intervals) { int n=intervals.size(); if(n<1)return {}; vector<Interval>ans; sort(intervals.begin(),intervals.end(),cmp); int left=0,right=left+1; for(int i=0;i<n;){ int j=i+1,t=i; int m=intervals[i].end; while(j<n&&intervals[j].start<=m){ m=max(intervals[j].end,m); ++j; ++i; } struct Interval *one=new Interval(intervals[t].start,m); ans.push_back(*one); i=j; } return ans; } };