Problem Description:
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]
.
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ struct cmpLess { bool operator ()(const Interval & a,const Interval & b) { return a.start<b.start; } }; class Solution { public: Interval merge(Interval a,Interval b) { Interval c; c.start=min(a.start,b.start); c.end=max(a.end,b.end); return c; } vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> res; if(intervals.size()==0) return res; Interval temp; int flag=0;//推断上一次是否有区间合并 sort(intervals.begin(),intervals.end(),cmpLess()); for(int i=1;i<intervals.size();i++) { if(flag==0) { if(intervals[i-1].end<intervals[i].start) res.push_back(intervals[i-1]); else { temp=merge(intervals[i-1],intervals[i]); flag=1; } } else { if(temp.end<intervals[i].start) { res.push_back(temp); flag=0; } else temp=merge(temp,intervals[i]); } } if(flag==0) res.push_back(intervals[intervals.size()-1]); else res.push_back(temp); return res; } };