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].
这里主要注意的是STL的sort的函数的comparor要写成static函数,而且参数采用值传递,不要用引用。
class Solution { public: static bool comp(Interval m1, Interval m2) { return m1.start < m2.start; } vector<Interval> merge(vector<Interval> &intervals) { sort(intervals.begin(), intervals.end(), Solution::comp); vector<Interval> ret; if (intervals.empty()) return ret; Interval pre(intervals[0]); for (int i = 0; i < intervals.size(); ++i) { if (intervals[i].start <= pre.end) { if (intervals[i].end > pre.end) pre.end = intervals[i].end; } else { ret.push_back(pre); pre = intervals[i]; } } ret.push_back(pre); return ret; } };
这样写。
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 static bool compare(const Interval &i1, const Interval &i2) { 13 return i1.start < i2.start; 14 } 15 vector<Interval> merge(vector<Interval> &intervals) { 16 sort(intervals.begin(), intervals.end(), compare); 17 vector<Interval> ans; 18 19 int n = intervals.size(); 20 for (int i = 0; i < n; ++i) { 21 if (i == n - 1 || intervals[i].end < intervals[i + 1].start) { 22 ans.push_back(intervals[i]); 23 } else { 24 intervals[i + 1].start = intervals[i].start; 25 if (intervals[i].end > intervals[i + 1].end) intervals[i + 1].end = intervals[i].end; 26 } 27 } 28 29 return ans; 30 } 31 };