Merge Intervals
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]
.
bool compare(const Interval & ls, const Interval & rs){ return ls.start < rs.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<Interval> ans; if (!intervals.size()) return ans; sort(intervals.begin(),intervals.end(),compare); Interval temp = intervals[0]; for(int i = 1; i < intervals.size(); i++){ if (temp.end >= intervals[i].start){ if (intervals[i].end > temp.end){ temp.end = intervals[i].end; } }else{ ans.push_back(temp); temp = intervals[i]; } } ans.push_back(temp); return ans; } };