/** * 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 cmp1957(const Interval& a, const Interval& b) { return a.start < b.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { sort(intervals.begin(), intervals.end(), cmp1957); vector<Interval> ans; if (intervals.size() < 1) return ans; int start = intervals[0].start; int end = intervals[0].end; for (int i = 1; i < intervals.size(); i++) { if (intervals[i].start <= end) { end = max(end, intervals[i].end); } else { ans.push_back(Interval(start, end)); start = intervals[i].start; end = intervals[i].end; } } ans.push_back(Interval(start, end)); return ans; } };
/** * 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) { vector<Interval> ans; if (intervals.size() == 0) return ans; sort(intervals.begin(), intervals.end(), [&](const Interval& a, const Interval& b) { return a.start < b.start; }); Interval tmp = *intervals.begin(); for (int i = 1; i < intervals.size(); i++) { if (intervals[i].start <= tmp.end) { tmp.end = max(tmp.end, intervals[i].end); } else { ans.push_back(tmp); tmp = intervals[i]; } } ans.push_back(tmp); return ans; } };
by 1957