题目:
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) {} * }; */ bool compare(const Interval &int1,const Interval &int2){ if(int1.start == int2.start){ return int1.end < int2.end; } return int1.start < int2.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { if(intervals.size() <= 1) return intervals; sort(intervals.begin(),intervals.end(),compare); vector<Interval>::size_type cur_index = 0, insert_index = 1,size = intervals.size(); int cur_last = intervals[0].end; while(insert_index != size){ if(intervals[insert_index].start <= cur_last && intervals[insert_index].end > intervals[cur_index].end){ cur_last = intervals[insert_index].end; intervals[cur_index].end = cur_last; }else if(intervals[insert_index].start > intervals[cur_index].end){ cur_index++; cur_last = intervals[insert_index].end; intervals[cur_index].start = intervals[insert_index].start; intervals[cur_index].end = intervals[insert_index].end; } insert_index++; } while(insert_index > cur_index + 1){ intervals.pop_back(); insert_index--; } return intervals; } };