leetcode - 57. Insert Interval

57. 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 wereinitially sorted according to their start times.

 

Example 1:

Given intervals [1,3],[6,9], insert andmerge [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].

 

Subscribe to see which companies asked thisquestion.

 

 

 

定义结构体interval,表示间隔。给定若干组已经排好序的间隔,然后在给一个新的间隔,最终进行merge操作后返回。

 

 

算法思想:

 

所谓的merge操作,将两个符合条件的结构体进行合并,条件为:

若结构体A的end值大于结构体B的start值;

然后A和B就要进行合并,合并成一个新的C。

C.start = min(A.start,B.start)

C.end= max(A.end,B.end)

 

遍历一次数组,然后不断地进行merge操作即可,复杂度为O(n),因为原始数组是有序的,。

 

步骤

1.      先将新的间隔插入有序的间隔。

2.      遍历数组,进行merge操作。


/**
 * 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 insert(vector& intervals, Interval newInterval) {
        vector r;
        int i;
        if(intervals.size() < 1){ r.push_back(newInterval);return r;}
        int endindex = intervals.size();
        for(i = 0 ; i < endindex ; i++){
           if(newInterval.start < intervals[i].start){
               intervals.insert(intervals.begin()+i,newInterval);
               break;
           }//end if
        }//for(i)
        if(i == endindex)intervals.push_back(newInterval);
        Interval now  = intervals[0];
        Interval temp;
        for( i = 1 ; i < intervals.size() ; i++){
            if(now.end < intervals[i].start ){
                r.push_back(now);
                now = intervals[i];
                continue;
            }
            else{
                now.end = max(now.end,intervals[i].end);
            }
        }//for(i)
        r.push_back(now);
        return r;
    }
};


 

你可能感兴趣的:(刷题,leetcode)