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]
.
主要是考虑几种情况:
1.起点重复的区间
2.某区间包含另一个区间
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool compInterval(const Interval& lhs,const Interval& rhs){ if(lhs.start == rhs.start){ return lhs.end < rhs.end; } return lhs.start < rhs.start; } class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { vector<Interval> res; int intervalsSize = intervals.size(); if(intervalsSize ==0){ return res; } sort(intervals.begin(),intervals.end(),compInterval); int i=0,j=1; while(i<intervalsSize){ int k = j; while((k < intervalsSize) && (intervals[k].start == intervals[k-1].start)){//处理相同起点的区间 k++; } i = k-1; int start = intervals[i].start; int end = intervals[i].end; while((k < intervalsSize) && (intervals[k].start > start && intervals[k].start <= end)){ end = max(end,intervals[k].end); k++; } if(k==j){ j = i; }else{ j = k-1; } res.push_back(Interval(intervals[i].start,end)); i = j+1; j = i+1; } return res; } };