标签:
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]
.
问题:给定一个区间集合,整合所有重叠的区间。
对区间集合按照 start 来排序,然后根据 intervals[i].start 和 res.lastElement.end 来整合即可。
1 int static comp(Interval t1, Interval t2){ 2 int res = (t2.start > t1.start); 3 return res; 4 } 5 6 vector<Interval> merge(vector<Interval>& intervals) { 7 8 vector<Interval> vt; 9 10 if (intervals.size() == 0) { 11 return vt; 12 } 13 14 std::sort(intervals.begin(), intervals.end(), comp); 15 16 vt.push_back(intervals[0]); 17 18 for (int i = 1 ; i < intervals.size(); i++) { 19 20 if (intervals[i].start <= vt.back().end) { 21 vt.back().end = max( vt.back().end, intervals[i].end); 22 }else{ 23 vt.push_back(intervals[i]); 24 } 25 } 26 27 return vt; 28 29 }
[LeetCode] 56. Merge Intervals 解题思路
标签:
原文地址:http://www.cnblogs.com/TonyYPZhang/p/5081336.html