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]
.
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9]
, insert and merge [2,5]
in as[1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge [4,9]
in as[1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
思路:
第一题的思路是先排序,然后依次向下比较归并。
第二题可以先插入再用第一题的归并方法。但是这里采用计算interval的覆盖位置的方法,相对复杂一些。
题解:
/** * 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 operator< (const Interval& i1, const Interval& i2) { return i1.start < i2.start; } class Solution { public: bool try_merge_next (Interval& i1, const Interval& i2) { if (i1.end < i2.start) return false; // not contacting else { i1.end = max (i1.end, i2.end); return true; } } vector<Interval> merge (vector<Interval>& intervals) { vector<Interval> ret; sort (begin (intervals), end (intervals)); if (!intervals.empty()) { ret.push_back (intervals.front()); for (auto & i : intervals) if (!try_merge_next (ret.back(), i)) ret.push_back (i); } return ret; } };
/** * 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: bool is_prior (const Interval& i, int val) { return (i.start < val && i.end < val); } bool is_after (const Interval& i, int val) { return (i.start > val && i.end > val); } vector<Interval> insert (vector<Interval>& intervals, Interval ni) { vector<Interval> ret; if (intervals.empty()) { ret.push_back (ni); return ret; } if (is_after (intervals.front(), ni.end)) { ret.push_back (ni); copy (begin (intervals), end (intervals), back_inserter (ret)); return ret; } if (is_prior (intervals.back(), ni.start)) { copy (begin (intervals), end (intervals), back_inserter (ret)); ret.push_back (ni); return ret; } // now we have to find the exact position auto iter = begin (intervals); auto last = end (intervals); while (is_prior (*iter, ni.start)) ret.push_back (*iter++); ni.start = min (ni.start, iter->start); while (iter != last && !is_after (*iter, ni.end)) ++iter; ni.end = max (ni.end, (iter - 1)->end); ret.push_back (ni); copy (iter, last, back_inserter (ret)); return ret; } };