您的位置:首页 > 其它

【简单】Lintcode 30:Insert Interval

2018-01-23 21:45 302 查看
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

Example

Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].
Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].

解题思路:

1、这道题一开始摸不着头脑,通过查看各位高手的代码,略懂。

2、简单的情况是插入一个原本就不重复的interval list,直接放在后面即可。

3、比较难的情况是插入一个有重复的元素,这时需要提取出重复两组元素start中最小的值与end中最大的值,防止数值重复。语言解释不太明白,具体看代码。

/**
* Definition of Interval:
* class Interval {
* public:
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
* }
*/

class Solution {
public:
/*
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval)
{
// write your code here
vector<Interval> &a = intervals;
Interval b = newInterval;
int i=0;

vector<Interval> ans;

//当插入元素不重复时,一次提取
while(i<a.size() && a[i].end < b.start)
{
ans.push_back(a[i++]);
}

//当插入元素与a[i]元素有重叠时,则提取两者start最小值,end最大值保证不重复
while(i<a.size() && b.end >= a[i].start)
{
b.start = min(b.start,a[i].start);
b.end = max(b.end,a[i].end);
++i;
}
ans.push_back(b);

//收尾
while(i<a.size())
{
ans.push_back(a[i++]);
}

return ans;

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