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) {} * }; */ #include <algorithm> bool myfunction (Interval A,Interval B) //C++ { return (A.start < B.start); } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> result; if(intervals.size() == 0) return result; sort(intervals.begin(),intervals.end(),myfunction); bool haveStart = false; int start ; int end ; for(int i = 0; i < intervals.size(); i++) { if(haveStart == false && i < intervals.size()) { start = intervals[i].start; end = intervals[i].end; haveStart = true; continue; } if(intervals[i].start <= end ) { if(intervals[i].end > end) end = intervals[i].end; } else { Interval tmp(start,end); result.push_back(tmp); start = intervals[i].start; end = intervals[i].end; } } if(haveStart) { Interval tmp(start,end); result.push_back(tmp); } return result; } };
原文地址:http://blog.csdn.net/chenlei0630/article/details/41488021