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]
.
分析:
题目要求对区间进行合并,首先必须对区间按照左边元素的大小进行排序,然后对排序后的数组进行遍历,合并。
能够合并的区间必须符合 a.begin <=b.begin <= a.end.
代码如下:
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: static int compare_Interval(Interval val1, Interval val2){ return val1.start < val2.start; } vector<Interval> merge(vector<Interval>& intervals) { vector<Interval> result; if (intervals.size()<=1) { return intervals; } sort(intervals.begin(),intervals.end(), compare_Interval); Interval node = intervals[0] ; for (int index=1; index<intervals.size(); index++) { Interval tmp = intervals[index] ; if (tmp.start > node.end) { result.push_back(node); node = tmp; continue; }else{ node.end = max(tmp.end, node.end); } } result.push_back(node); return result; } };
原文地址:http://blog.csdn.net/sunao2002002/article/details/46335189