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

我的解法

我感觉是二分查找的应用
设插入的区间是newInterval 为[a,b]
通过二分查找找到最大的索引h,h是满足 intervals[h].start<=b;
通过二分查找找到最小的索引l,l是满足 intervals[l].end>=a;
如果l>h,在l前插入直接新区间即可;
如果l==h,将intervals[l]区间与newInterval合并即可;
如果l<h,需要将intervals[l]至intervals[h]区间与newInterval合并。

代码

/**
 * 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> insert(vector<Interval> &intervals, Interval newInterval) {
        int i=intervals.size();
        //if(0==i)
        int high=i-1;
        int low=0;
        int h=-1;
        int l=i;
        while(low<=high){
            int mid=(low+high)/2;
            if(intervals[mid].start>newInterval.end){
                high=mid-1;
            }else {
                h=mid;
                low=mid+1;
            }
        }
        if(h==-1){
            intervals.insert(intervals.begin(),newInterval);
            return intervals;
        }
        high=i-1;
        low=0;
        while(low<=high){
            int mid=(low+high)/2;
            if(intervals[mid].end<newInterval.start){
                low=mid+1;
                
            }else {
                l=mid;
                high=mid-1;
            }
        }   
        if(l==i){
            intervals.push_back(newInterval);
            return intervals;
        }
        if(l==h){
            intervals[l].start=std::min(intervals[l].start,newInterval.start);
            intervals[l].end=std::max(intervals[l].end,newInterval.end);
        }else if(l>h){
            intervals.insert(intervals.begin()+l,newInterval);
        }else {
            newInterval.start=std::min(intervals[l].start,newInterval.start);
            newInterval.end=std::max(intervals[h].end,newInterval.end);
            intervals.erase(intervals.begin()+l,intervals.begin()+h+1);//+1
            intervals.insert(intervals.begin()+l,newInterval);
        }
        return intervals;
    }
};


你可能感兴趣的:(LeetCode,insert,interval)