标签:
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]
.
思路:排序后,再比较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) {} * }; */ bool cmp(const Interval &a, const Interval &b) { return a.start < b.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { int n = intervals.size(); vector<Interval> ans; sort(intervals.begin(), intervals.end(), cmp); for (int i = 0; i < intervals.size(); i++) { if (ans.size() == 0) ans.push_back(intervals[i]); else { int m = ans.size(); if (ans[m-1].start <= intervals[i].start && ans[m-1].end >= intervals[i].start) ans[m-1].end = max(ans[m-1].end, intervals[i].end); else ans.push_back(intervals[i]); } } return ans; } };
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/44265383