Merge Intervals
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]
.
思路:
先对数据进行排序,然后逐个插入。注意在使用sort的时候,最开始出现<unresolved overloaded function type>错误,后来把myCmp改成static的以后就解决了。
代码:
1 int max(int a, int b){ 2 if(a > b) 3 return a; 4 return b; 5 } 6 static bool myCmp(const Interval &a, const Interval &b){ 7 if(a.start == b.start) 8 return a.end < b.end; 9 return a.start < b.start; 10 } 11 vector<Interval> merge(vector<Interval> &intervals) { 12 int n = intervals.size(); 13 if(n <= 1) 14 return intervals; 15 sort(intervals.begin(), intervals.end(), myCmp); 16 vector<Interval> result; 17 int start = intervals[0].start, end = intervals[0].end; 18 for(int i = 1; i < n; i++){ 19 if(intervals[i].start > end){ 20 result.push_back(Interval(start, end)); 21 start = intervals[i].start; 22 end = intervals[i].end; 23 } 24 else{ 25 end = max(end, intervals[i].end); 26 } 27 } 28 result.push_back(Interval(start, end)); 29 return result; 30 }
第二遍:
1 static bool myCmp(const Interval &a, const Interval &b){ 2 if(a.start == b.start) 3 return a.end < b.end; 4 return a.start < b.start; 5 } 6 vector<Interval> merge(vector<Interval> &intervals) { 7 vector<Interval> result; 8 if(!intervals.empty()){ 9 sort(intervals.begin(), intervals.end(), myCmp); 10 int start = intervals[0].start, end = intervals[0].end; 11 for(int i = 1; i < intervals.size(); i++){ 12 if(intervals[i].start <= end) 13 end = end > intervals[i].end ? end : intervals[i].end; 14 else{ 15 result.push_back(Interval(start, end)); 16 start = intervals[i].start; 17 end = intervals[i].end; 18 } 19 } 20 result.push_back(Interval(start, end)); 21 } 22 return result; 23 }