首页 > 代码库 > Insert Interval

Insert Interval

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].

思路:看了网上的解法,貌似直接遍历就行了。写了个二分查找的,不如直接遍历来得直观,作死了!

 1 class Solution { 2 public: 3     vector<Interval> insert( vector<Interval> &intervals, Interval newInterval ) { 4         int start = binary_search( intervals, newInterval.start ); 5         if( start < 0 ) { start = 0; } 6         if( start < (int)intervals.size() && intervals[start].end < newInterval.start ) { ++start; } 7         if( start >= (int)intervals.size() ) { 8             intervals.push_back( newInterval ); 9             return intervals;10         }11         int end = binary_search( intervals, newInterval.end );12         if( end < 0 ) {13             intervals.insert( intervals.begin(), newInterval );14             return intervals;15         }16         if( start <= end ) {17             intervals[start].start = min( intervals[start].start, newInterval.start );18             intervals[start].end = max( intervals[end].end, newInterval.end );19             intervals.erase( intervals.begin()+start+1, intervals.begin()+end+1 );20         } else {21             intervals.insert( intervals.begin()+start, newInterval );22         }23         return intervals;24     }25 private:26     int binary_search( vector<Interval> &intervals, int val ) {27         int start = 0, end = (int)intervals.size()-1;28         while( start <= end ) {29             int middle = ( start + end ) / 2;30             if( intervals[middle].start == val ) { return middle; }31             if( intervals[middle].start < val ) {32                 start = middle + 1;33             } else {34                 end = middle - 1;35             }36         }37         return end;38     }39 };

 

Insert Interval