【Insert Interval】cpp
题目:
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)
{
vector<Interval> ret;
int i = ;
// search for start insert position
for ( ; i<intervals.size(); ++i )
{
if ( newInterval.start > intervals[i].end )
{
ret.push_back(intervals[i]);
}
else
{
break;
}
}
// newInterval larger than all the existed intervals
if ( i==intervals.size() )
{
ret.push_back(newInterval);
return ret;
}
int start = std::min( intervals[i].start, newInterval.start );
// search for the end insert position
for ( ;i<intervals.size();++i )
{
if ( newInterval.end <= intervals[i].end ) break;
}
// newInterval end is larger than all the range
if ( i==intervals.size() )
{
ret.push_back(Interval(start, newInterval.end));
return ret;
}
if ( newInterval.end<intervals[i].start )
{
ret.push_back(Interval(start,newInterval.end));
ret.insert(ret.end(), intervals.begin()+i, intervals.end());
return ret;
}
if ( newInterval.end==intervals[i].start )
{
ret.push_back(Interval(start,intervals[i].end));
if ( i<intervals.size()- )
{
ret.insert(ret.end(), intervals.begin()+i+, intervals.end());
}
return ret;
}
if ( newInterval.end > intervals[i].start )
{
ret.push_back(Interval(start,intervals[i].end));
if ( i<intervals.size()- )
{
ret.insert(ret.end(), intervals.begin()+i+,intervals.end());
}
return ret;
}
}
};
tips:
这道题的总体感觉就是很繁琐,因为要考虑各种边界情况,等或者不等;虽然能AC但是这一版代码比较丑陋。
看能不能改一版漂亮一些的。
===================================
学习了一个迭代版的,代码很漂亮,但是会超时。
/**
* 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>::iterator it = intervals.begin();
while ( it!=intervals.end() )
{
if ( newInterval.end < it->start )
{
intervals.insert(it, newInterval);
return intervals;
}
else if ( it->end < newInterval.start )
{
it++;
}
else
{
newInterval.start = std::min(newInterval.start, it->start);
newInterval.end = std::max(newInterval.end, it->end);
intervals.erase(it);
}
}
intervals.insert(intervals.end(), newInterval);
return intervals;
}
};
=======================================
还是觉得自己的第一次AC的代码太乱,网上搜了一下,模仿大神(http://yucoding.blogspot.sg/2013/01/leetcode-question-35-insert-interval.html)重新写了一版AC的代码。
/**
* 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> ret;
// insert the new Interval
vector<Interval>::iterator it = intervals.begin();
for( ; it!=intervals.end(); ++it )
{
if ( newInterval.start < it->start )
{
intervals.insert(it, newInterval);
break;
}
}
if ( it==intervals.end() )
{
intervals.insert(it, newInterval);
}
// merge the intervals
ret.push_back(*intervals.begin());
for ( it=intervals.begin()+; it!=intervals.end(); ++it )
{
if ( it->start > ret.back().end )
{
ret.push_back(*it);
}
else
{
ret.back().start = std::min(ret.back().start, it->start);
ret.back().end = std::max(ret.back().end, it->end);
}
}
return ret;
}
};
tips:
这一版的代码采用了新的思路。
1. 题中给定了原有的interval集合是按照start排好序的;因此,首先要找到合适的位置,将newInterval插进去。
2. 插进去之后,就有可能存在intervals之间存在overlap的情况,因此再merge(http://www.cnblogs.com/xbf9xbf/p/4557153.html)一遍就OK。
在merge的过程中有个细节:不用维护start和end,ret.back().start和ret.back().end就可以。这个比自己原来写的merge intervals要好,学习了这个细节。
=============================================
第二次过这道题,直接参照的最简洁的思路:
(1)先insert:条件是i->end > newInterval.start(即肯定有重叠) 根据newInterval.start的大小先插进去
(2)再merge:修改ret.back().start和ret.back().end的值
/**
* 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> ret;
vector<Interval>::iterator i=intervals.begin();
for ( ; i!=intervals.end(); ++i )
{
if ( i->end > newInterval.start ){
intervals.insert(i, newInterval);
break;
}
}
if ( i==intervals.end() ) intervals.insert(i, newInterval);
ret.push_back(*intervals.begin());
for ( i=intervals.begin()+; i!=intervals.end(); ++i )
{
if ( i->start > ret.back().end )
{
ret.push_back(*i);
}
else
{
ret.back().start = min(ret.back().start, i->start);
ret.back().end = max(ret.back().end, i->end);
}
}
return ret;
}
};
=========================================
第三次过这道题,终于理清楚了。
类似这样的图形去理解interval insert 和 merge
1
11
111
111
11
1
【Insert Interval】cpp的更多相关文章
- 【Merge Intervals】cpp
题目: Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6], ...
- 【Search Insert Position 】cpp
题目: Given a sorted array and a target value, return the index if the target is found. If not, return ...
- 【Add binary】cpp
题目: Given two binary strings, return their sum (also a binary string). For example,a = "11" ...
- 【LRU Cache】cpp
题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...
- hdu 4739【位运算】.cpp
题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...
- Hdu 4734 【数位DP】.cpp
题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...
- 【ZigZag Conversion】cpp
题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l ...
- 【Multiply Strings】cpp
题目: Given two numbers represented as strings, return multiplication of the numbers as a string. Note ...
- 【Minimum Window】cpp
题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...
随机推荐
- April 27 2017 Week 17 Thursday
Had I not seen the sun, I could have borne the shade. 我本可以忍受黑暗,如果我不曾见过阳光. A poem by Emily Dickinson, ...
- IOS 拦截所有push进来的子控制器
/** * 能拦截所有push进来的子控制器 */ - (void)pushViewController:(UIViewController *)viewController animated:(BO ...
- TCP的可靠连接是如何产生的?
http://bbs.csdn.net/topics/190011812 看过TCP/IP的源代码没?tcp中所谓的连接只是在tcp的tcb中存储了对端的地址信息,并且记录连接的状态,通过重发之类的来 ...
- 机器学习实战之Logistic回归
Logistic回归一.概述 1. Logistic Regression 1.1 线性回归 1.2 Sigmoid函数 1.3 逻辑回归 1.4 LR 与线性回归的区别 2. LR的损失函数 3. ...
- caffe中的sgd,与激活函数(activation function)
caffe中activation function的形式,直接决定了其训练速度以及SGD的求解. 在caffe中,不同的activation function对应的sgd的方式是不同的,因此,在配置文 ...
- matlab vs联调
vs 和matlab联调,最近真的把我搞挂了要. 首先,怎么进入联调呢.在vs里先设置一下. vs:tools->attach to process,选择matlab,注意此时matlab一定是 ...
- Eclipse Git 插件 基本操作一【learn】
安装GIT插件: 我的Eclipse版本为: Oxygen.2 Release (4.7.2),所以自带GIT插件,跳过安装. GIT插件配置: ①.添加好用户名和邮箱 注意下输入格式:user.na ...
- io与Nio的区别及实用场景
https://blog.csdn.net/wodeyuer125/article/details/39475207
- Python 初始—(函数·)
过程是没有返回值的函数,有一系列的函数组合和逻辑功能结合即为过程: def 定义函数: def 函数名(): print("") 位置参数和关键字调用,根据位置参数优先,关键字参数 ...
- Redis连接工具类
Redis连接工具类 导包 测试一下(junit) package com.test; import org.junit.Test; import redis.clients.jedis.Jedis; ...