题目如下:
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].
分析如下:
由于输入的一堆intervals已经是排好序的了,所以接下来可以用二分查找找到new interval应该插入的合适的位置,这样新形成的intervals会比原来的intervals的数量多一。接下来对新的intervals进行merge就可以了, merge参考上面一道题目 Merge Intervals.
我的代码:
//72ms /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ //[[3,1],[5,6]], [1,1] //[[3,1],[5,6]], [7,8] struct MyInterval{ bool operator()(Interval interval1, Interval interval2) { return (interval1.start < interval2.start); } } my_interval; class Solution { public: // void print_interval_vector(vector<Interval> interval_vec) { // for (int i = 0; i < interval_vec.size(); ++i) { // std::cout<<"["<<interval_vec[i].start<<", "<<interval_vec[i].end<<"]"<<", "; // } // std::cout<<std::endl; // } // vector<Interval> make_input(int input[][2], int len) { // vector<Interval> res; // for (int i = 0; i < len; ++i) { // Interval a; // a.start = input[i][0]; // a.end = input[i][1]; // res.push_back(a); // std::cout<<"a.start = "<<a.start<<", a.end="<<a.end<<std::endl; // } // return res; // } vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> final; //std::sort(intervals.begin(), intervals.end(), my_interval); //unnecessary to sort final.push_back(intervals[0]); for (int i = 1; i < intervals.size(); ++i) { if (intervals[i].start <= final.back().end) { final.back().end = intervals[i].end > final.back().end ? intervals[i].end : final.back().end; } else { final.push_back(intervals[i]); } } return final; } vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> result; if (intervals.size() == 0) { result.push_back(newInterval); return vector<Interval> result; } // first, insert int start_index = 0, end_index = intervals.size(), mid_index = 0, insert_index = -1; //std::sort(intervals.begin(), intervals.end(), my_interval); //unnecessary to sort while (start_index <= end_index) { mid_index = start_index + (end_index - start_index) / 2; if (intervals[mid_index].start == newInterval.start) { insert_index = mid_index; break; } else if (intervals[mid_index].start > newInterval.start) { end_index = mid_index - 1; } else { start_index = mid_index + 1;//this can be concluded from the example above } } if (insert_index == -1) insert_index = start_index; if (insert_index > intervals.size()) insert_index = intervals.size(); if (insert_index < 0) insert_index = 0; intervals.insert(intervals.begin() + insert_index, newInterval); //second, merge return merge(intervals); } };