【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 ...
随机推荐
- UVA-147 Dollars---完全背包+打表
题目链接: https://vjudge.net/problem/UVA-147 题目大意: 给定11种面值分别为$100, $50, $20, $10, and $5 notes and $2, $ ...
- LA 3635 派
题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_ ...
- 木棒,POJ(1011)
题目链接:http://poj.org/problem?id=1011 解题报告: #include <cstdio> #include <cstring> #include ...
- 2017.11.5 Java Web ----案例:数据库访问JavaBean的设计
(12)案例----数据库访问JavaBean的设计 例题:数据库操作在一个Web应用程序中的后台处理中占有大比重,设计一组JavaBean封装数据库的基本操作供上层模块调用,提高程序的可移植性. [ ...
- Mybatis中的DataSource配置
dataSource 的类型可以配置成其内置类型之一,如 UNPOOLED,POOLED,JNDI. 1.如果将类型设置成 UNPOOLED,MyBatis 会为每一个数据库操作创建一个新的连接,并关 ...
- ajaxfileup.js
<img id="tinyPic" class="user-icon" :src="headPortrait"><inpu ...
- 3.vue引入axios全局配置
前言: Vue官方推荐使用axios来进行异步访问. axios文档参考:axios中文文档 开始搭建: 1.引入axios (1)打开终端 win+R (2)切换到项目路径: g: cd Webap ...
- 洛谷 P3372 线段树1
这是一道模板题 线段树介绍https://www.cnblogs.com/nvwang123/p/10420832.html #include<bits/stdc++.h> using n ...
- Linux下文件的压缩与解压缩
一.zip格式 zip可能是目前使用的最多的文档压缩格式.它最大的优点就是在不同的操作系统平台上使用.缺点就是支持 的压缩率不是很高,而tar.gz和tar.bz2在压缩率方面做得非常好. 我们可以使 ...
- JS - 把类似document.querySelectorAll(".xxx")、document.getElementsByName("xxx")这种方法的返回结果转换成数组对象
var btns = document.querySelectorAll(".btn");console.log(btns instanceof Array); // falseb ...