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]
.
class Solution { struct IntvTreeNode{ int start; int end; int max; IntvTreeNode* left; IntvTreeNode* right; IntvTreeNode(){ } IntvTreeNode(int ps,int pe){ start=ps; end=pe; max=-1; if(ps==pe-1){ left=NULL; right=NULL; return; } int mid=(ps+pe)/2; left=new IntvTreeNode(ps,mid); right=new IntvTreeNode(mid,pe); } }; void Insert(int start,int end,IntvTreeNode* root){ if(root->max==root->end-root->start)return; if(root->start==root->end-1){ if(start!=end) root->max=1; else root->max=0; return; } int mid=(root->start+root->end)/2; if(end<mid){ Insert(start,end,root->left); } else if(end==mid){ if(start==end)Insert(start,end,root->right); else Insert(start,end,root->left); } else if(start>=mid){ Insert(start,end,root->right); } else{ Insert(start,mid,root->left); Insert(mid,end,root->right); } if(root->left->max==root->left->end-root->left->start &&root->right->max==root->right->end-root->right->start) root->max=root->end-root->start; } void Output(vector<int>& ret,IntvTreeNode* root){ if(root->max==root->end-root->start){ ret.push_back(root->start); ret.push_back(root->end); return; } else if(root->max==0){ ret.push_back(root->start); ret.push_back(root->start); return; } if(root->start==root->end-1)return; Output(ret,root->left); Output(ret,root->right); } public: vector<Interval> merge(vector<Interval> &intervals) { // Note: The Solution object is instantiated only once and is reused by each test case. if(intervals.size()==0)return intervals; map<int,int> ma; set<int> se; for(int i=0;i<intervals.size();i++){ se.insert(intervals[i].start); se.insert(intervals[i].end); } int index=0; for(set<int>::iterator it=se.begin();it!=se.end();it++){ ma[*it]=index; index++; } IntvTreeNode* root =new IntvTreeNode(0,index); for(int i=0;i<intervals.size();i++){ int start=ma[intervals[i].start]; int end=ma[intervals[i].end]; Insert(start,end,root); } vector<int> vec; Output(vec,root); bool start=false; int size; vector<Interval>ret; vector<int> mam(se.begin(),se.end()); ret.push_back(Interval(mam[vec[0]],mam[vec[1]])); for(int i=2;i<vec.size();i+=2){ if(vec[i-1]==vec[i]) { ret[ret.size()-1].end=mam[vec[i+1]]; } else ret.push_back(Interval(mam[vec[i]],mam[vec[i+1]])); } return ret; } };