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) {} * }; */ class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { if (intervals.size() <= 1) return intervals; sort(intervals.begin(), intervals.end(), [](const Interval &a, const Interval &b) {return a.start < b.start;}); size_t j = 0; for (size_t i = j+1; i<intervals.size(); i++) { if (intervals[j].end >= intervals[i].start) intervals[j].end = max(intervals[j].end, intervals[i].end); else intervals[++j] = intervals[i]; } intervals.erase(intervals.begin()+j+1, intervals.end()); return intervals; } };
该算法在leetcode上实行执行时间为20ms。
基本思路:
1.利用自定的比较函数进行排序,以达到按start进行升序。
2. 利用remove-duplicates-from-sorted-array的思路进行归并
原文地址:http://blog.csdn.net/elton_xiao/article/details/44701403