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

思路:

主要工作有两点:第一找到插入位置;第二确定是替换还是新增。

代码:

/**
 * 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) {
        if(intervals.size()==0)
        {
            vector<Interval> r;
            r.push_back(newInterval);
            return r;
        }
        else
        {
            int begin = 0;
            int end = intervals.size()-1;
            if(newInterval.end < intervals[begin].start)
            {
                intervals.insert(intervals.begin(),newInterval);
            }
            else if(newInterval.start > intervals[end].end)
            {
                intervals.insert(intervals.end(),newInterval);
            }
            else
            {
                while(end>=begin)
                {
                    if(newInterval.end < intervals[end].start)
                    {
                        end--;
                    }else if(newInterval.start > intervals[begin].end)
                    {
                        begin++;
                    }
                    else
                    {
                        break;
                    }
                };
                if(end>=begin)
                {
                    int s=intervals[begin].start>newInterval.start?newInterval.start:intervals[begin].start;
                    int e=intervals[end].end<newInterval.end?newInterval.end:intervals[end].end;
                    intervals.erase(intervals.begin()+begin, intervals.begin()+end+1);
                    intervals.insert(intervals.begin()+begin,*(new Interval(s,e)));
                }
                else
                {
                    intervals.insert(intervals.begin()+begin,newInterval);
                }
            }
            return intervals;
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17557481
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞