题目:

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].

代码:

  1. /**
  2. * Definition for an interval.
  3. * struct Interval {
  4. * int start;
  5. * int end;
  6. * Interval() : start(0), end(0) {}
  7. * Interval(int s, int e) : start(s), end(e) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<Interval> insert(vector<Interval>& intervals, Interval newInterval)
  13. {
  14. vector<Interval> ret;
  15. int i = ;
  16. // search for start insert position
  17. for ( ; i<intervals.size(); ++i )
  18. {
  19. if ( newInterval.start > intervals[i].end )
  20. {
  21. ret.push_back(intervals[i]);
  22. }
  23. else
  24. {
  25. break;
  26. }
  27. }
  28. // newInterval larger than all the existed intervals
  29. if ( i==intervals.size() )
  30. {
  31. ret.push_back(newInterval);
  32. return ret;
  33. }
  34. int start = std::min( intervals[i].start, newInterval.start );
  35. // search for the end insert position
  36. for ( ;i<intervals.size();++i )
  37. {
  38. if ( newInterval.end <= intervals[i].end ) break;
  39. }
  40. // newInterval end is larger than all the range
  41. if ( i==intervals.size() )
  42. {
  43. ret.push_back(Interval(start, newInterval.end));
  44. return ret;
  45. }
  46. if ( newInterval.end<intervals[i].start )
  47. {
  48. ret.push_back(Interval(start,newInterval.end));
  49. ret.insert(ret.end(), intervals.begin()+i, intervals.end());
  50. return ret;
  51. }
  52. if ( newInterval.end==intervals[i].start )
  53. {
  54. ret.push_back(Interval(start,intervals[i].end));
  55. if ( i<intervals.size()- )
  56. {
  57. ret.insert(ret.end(), intervals.begin()+i+, intervals.end());
  58. }
  59. return ret;
  60. }
  61. if ( newInterval.end > intervals[i].start )
  62. {
  63. ret.push_back(Interval(start,intervals[i].end));
  64. if ( i<intervals.size()- )
  65. {
  66. ret.insert(ret.end(), intervals.begin()+i+,intervals.end());
  67. }
  68. return ret;
  69. }
  70. }
  71. };

tips:

这道题的总体感觉就是很繁琐,因为要考虑各种边界情况,等或者不等;虽然能AC但是这一版代码比较丑陋。

看能不能改一版漂亮一些的。

===================================

学习了一个迭代版的,代码很漂亮,但是会超时。

  1. /**
  2. * Definition for an interval.
  3. * struct Interval {
  4. * int start;
  5. * int end;
  6. * Interval() : start(0), end(0) {}
  7. * Interval(int s, int e) : start(s), end(e) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<Interval> insert(vector<Interval>& intervals, Interval newInterval)
  13. {
  14. vector<Interval>::iterator it = intervals.begin();
  15. while ( it!=intervals.end() )
  16. {
  17. if ( newInterval.end < it->start )
  18. {
  19. intervals.insert(it, newInterval);
  20. return intervals;
  21. }
  22. else if ( it->end < newInterval.start )
  23. {
  24. it++;
  25. }
  26. else
  27. {
  28. newInterval.start = std::min(newInterval.start, it->start);
  29. newInterval.end = std::max(newInterval.end, it->end);
  30. intervals.erase(it);
  31. }
  32. }
  33. intervals.insert(intervals.end(), newInterval);
  34. return intervals;
  35. }
  36. };

=======================================

还是觉得自己的第一次AC的代码太乱,网上搜了一下,模仿大神(http://yucoding.blogspot.sg/2013/01/leetcode-question-35-insert-interval.html)重新写了一版AC的代码。

  1. /**
  2. * Definition for an interval.
  3. * struct Interval {
  4. * int start;
  5. * int end;
  6. * Interval() : start(0), end(0) {}
  7. * Interval(int s, int e) : start(s), end(e) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<Interval> insert(vector<Interval>& intervals, Interval newInterval)
  13. {
  14. vector<Interval> ret;
  15. // insert the new Interval
  16. vector<Interval>::iterator it = intervals.begin();
  17. for( ; it!=intervals.end(); ++it )
  18. {
  19. if ( newInterval.start < it->start )
  20. {
  21. intervals.insert(it, newInterval);
  22. break;
  23. }
  24. }
  25. if ( it==intervals.end() )
  26. {
  27. intervals.insert(it, newInterval);
  28. }
  29. // merge the intervals
  30. ret.push_back(*intervals.begin());
  31. for ( it=intervals.begin()+; it!=intervals.end(); ++it )
  32. {
  33. if ( it->start > ret.back().end )
  34. {
  35. ret.push_back(*it);
  36. }
  37. else
  38. {
  39. ret.back().start = std::min(ret.back().start, it->start);
  40. ret.back().end = std::max(ret.back().end, it->end);
  41. }
  42. }
  43. return ret;
  44. }
  45. };

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的值

  1. /**
  2. * Definition for an interval.
  3. * struct Interval {
  4. * int start;
  5. * int end;
  6. * Interval() : start(0), end(0) {}
  7. * Interval(int s, int e) : start(s), end(e) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
  13. vector<Interval> ret;
  14. vector<Interval>::iterator i=intervals.begin();
  15. for ( ; i!=intervals.end(); ++i )
  16. {
  17. if ( i->end > newInterval.start ){
  18. intervals.insert(i, newInterval);
  19. break;
  20. }
  21. }
  22. if ( i==intervals.end() ) intervals.insert(i, newInterval);
  23. ret.push_back(*intervals.begin());
  24. for ( i=intervals.begin()+; i!=intervals.end(); ++i )
  25. {
  26. if ( i->start > ret.back().end )
  27. {
  28. ret.push_back(*i);
  29. }
  30. else
  31. {
  32. ret.back().start = min(ret.back().start, i->start);
  33. ret.back().end = max(ret.back().end, i->end);
  34. }
  35. }
  36. return ret;
  37. }
  38. };

=========================================

第三次过这道题,终于理清楚了。

类似这样的图形去理解interval insert 和 merge

1

11

111

111

11

1

【Insert Interval】cpp的更多相关文章

  1. 【Merge Intervals】cpp

    题目: Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6], ...

  2. 【Search Insert Position 】cpp

    题目: Given a sorted array and a target value, return the index if the target is found. If not, return ...

  3. 【Add binary】cpp

    题目: Given two binary strings, return their sum (also a binary string). For example,a = "11" ...

  4. 【LRU Cache】cpp

    题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...

  5. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  6. 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~ ...

  7. 【ZigZag Conversion】cpp

    题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l ...

  8. 【Multiply Strings】cpp

    题目: Given two numbers represented as strings, return multiplication of the numbers as a string. Note ...

  9. 【Minimum Window】cpp

    题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...

随机推荐

  1. 特殊矩阵的压缩存储(转自chunlanse2014)

    对称矩阵 对于一个矩阵结构显然用一个二维数组来表示是非常恰当的,但在有些情况下,比如常见的一些特殊矩阵,如三角矩阵.对称矩阵.带状矩阵.稀疏矩阵等,从节约存储空间的角度考虑,这种存储是不太合适的.下面 ...

  2. 页面文本超出后CSS实现隐藏的方法

    text-overflow: ellipsis !important; white-space: nowrap !important; overflow: hidden !important; dis ...

  3. [USACO07FEB]银牛派对Silver Cow Party---最短路模板题

    银牛排队 对于我这种蒟蒻来说,还是不要跑一次单元最短路.跑两次好写呀(- ̄▽ ̄)- 而题目中是有向图.如果如果按照题意进行最短路的话.就会出现一个单终点最短路和一个单起点最短路 对于单起点自然就是套模 ...

  4. 第19章 通讯的基本概念—零死角玩转STM32-F429系列

    第19章     通讯的基本概念 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/firege ...

  5. idea和eclipse中getAbsolutePath()方法获取值不同

    项目中,使用嵌入式tomcat启动web工程(具体使用请度娘,关键字: tomcat embeded) 启动时,设置tomcat path的代码如下: Embedded tomcat = new Em ...

  6. JavaScript: window.onload = function() {} 里面的函数不执行

    问题:写了一个最简单的页面.在script标签中使用的 window.onload = function() { function add() { //... } } 页面上:<div oncl ...

  7. spring-bean(xml方式DI)

    三种属性注入方式 构造函数注入 1.在Bean实体中写入构造函数(带参构造) 2. <bean id=”该bean的名称” class=”注入的bean的全路径”> <constru ...

  8. javascript常用代码片段

    /** * * @desc 判断两个数组是否相等 * @param {Array} arr1 * @param {Array} arr2 * @return {Boolean} */ function ...

  9. 在ubuntu上安装subline

    Sublime Text is a most popular, lightweight and smart cross-platform text and source code editor wit ...

  10. Redis在windows下安装过程(转)

    (转)原文:http://www.cnblogs.com/M-LittleBird/p/5902850.html 要使redis在PHP下运行, 需在PHP文件下的ext扩展文件夹中添加扩展文件 ph ...