【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 ...
随机推荐
- 特殊矩阵的压缩存储(转自chunlanse2014)
对称矩阵 对于一个矩阵结构显然用一个二维数组来表示是非常恰当的,但在有些情况下,比如常见的一些特殊矩阵,如三角矩阵.对称矩阵.带状矩阵.稀疏矩阵等,从节约存储空间的角度考虑,这种存储是不太合适的.下面 ...
- 页面文本超出后CSS实现隐藏的方法
text-overflow: ellipsis !important; white-space: nowrap !important; overflow: hidden !important; dis ...
- [USACO07FEB]银牛派对Silver Cow Party---最短路模板题
银牛排队 对于我这种蒟蒻来说,还是不要跑一次单元最短路.跑两次好写呀(- ̄▽ ̄)- 而题目中是有向图.如果如果按照题意进行最短路的话.就会出现一个单终点最短路和一个单起点最短路 对于单起点自然就是套模 ...
- 第19章 通讯的基本概念—零死角玩转STM32-F429系列
第19章 通讯的基本概念 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/firege ...
- idea和eclipse中getAbsolutePath()方法获取值不同
项目中,使用嵌入式tomcat启动web工程(具体使用请度娘,关键字: tomcat embeded) 启动时,设置tomcat path的代码如下: Embedded tomcat = new Em ...
- JavaScript: window.onload = function() {} 里面的函数不执行
问题:写了一个最简单的页面.在script标签中使用的 window.onload = function() { function add() { //... } } 页面上:<div oncl ...
- spring-bean(xml方式DI)
三种属性注入方式 构造函数注入 1.在Bean实体中写入构造函数(带参构造) 2. <bean id=”该bean的名称” class=”注入的bean的全路径”> <constru ...
- javascript常用代码片段
/** * * @desc 判断两个数组是否相等 * @param {Array} arr1 * @param {Array} arr2 * @return {Boolean} */ function ...
- 在ubuntu上安装subline
Sublime Text is a most popular, lightweight and smart cross-platform text and source code editor wit ...
- Redis在windows下安装过程(转)
(转)原文:http://www.cnblogs.com/M-LittleBird/p/5902850.html 要使redis在PHP下运行, 需在PHP文件下的ext扩展文件夹中添加扩展文件 ph ...