您的位置:首页 > 其它

[LeetCode] Insert Interval

2015-08-19 16:11 323 查看
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].

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中的元素都是non-overlapping的,所以即使要找到两个下标sz1和sz2,使得newInterval与他们对应的元素有交集

这里有四种情况

1)sz1<0,则将newInterval放到vector的头位置,vector是顺序容器,不支持push_front的操作(当然也不支持pop_front)

2)sz2=size()-1,则将newInterval push_back即可

3)sz1>sz2 说明newInterval是插入在sz1和sz2之间的

4)sz1<=sz2 说明newInterval与sz1和sz2的元素要融合一下再插入

这里先巩固下顺序容器中访问,插入和删除的操作

//at和下标操作适用于string,vector,deque和array
c

c.at(n) 区别在于下标n越界时是否抛出异常
c.back()    返回尾元素的引用
c.front()   返回头元素的引用

//向顺序容器中添加元素
//vector和string不支持push_front和emplace_front
c.push_back()
c.push_front()
c.insert(p,t)       在迭代器p指向的元素之前插入t
c.insert(p,n,t)
c.inset(p,b,e)      在迭代器p之前插入迭代器b和e范围内的元素。
c.insert(p,il)      p之前插入初始化列表

insert返回的是新添加的第一个元素的迭代器
list<string> lst;
auto iter = lst.begin();
while(cin>>word)
iter = lst.insert(iter, word);          //等价于push_front

//顺序容器的删除
vector和string不支持pop_front
c.pop_back()
c.pop_front()
c.erase(p)
c.erase(b,e)        //删除[b,e)之间的元素,e指向的是一个最后一个被删除的元素后一个的迭代器

earse返回的是被删除元素之后的迭代器
elem1 = slist.erase(elem1,elem2);           //调用后elem1==elem2


/**
* 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) {
vector<Interval> new_intervals;
if(intervals.size()==0) return vector<Interval>{newInterval};
if(newInterval.end<intervals.front().start)  {intervals.insert(intervals.begin(),newInterval); return intervals;}
if(newInterval.start>intervals.back().end)  {intervals.push_back(newInterval); return intervals;}
vector<Interval>::size_type sz1,sz2;
sz1= 0;
sz2= intervals.size()-1;
while(intervals[sz1].end<newInterval.start)     ++sz1;
while(intervals[sz2].start>newInterval.end)     --sz2;
if(sz1<=sz2){
newInterval = Interval(min(newInterval.start,intervals[sz1].start),max(newInterval.end,intervals[sz2].end));
intervals.erase(intervals.begin()+sz1,intervals.begin()+sz2+1);
//intervals.insert(intervals.begin()+sz1,newInterval);
}
intervals.insert(intervals.begin()+sz1,newInterval);

return intervals;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: