Interval的合并时比较常见的一类题目,网上的Amazon面经上也有面试这道题的记录。这里以LeetCode上的例题做练习。

Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

/**
* 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> merge(vector<Interval> &intervals) {
}
};

我的解法是新定义一个vector<Interval> res,然后每次从intervals中提一个Interval出来,如果这个Interval和res中已有的某个Interval有overlap,就合并成新的Interval,又放回intervals中。

循环终止条件是intervals.size() == 0。

class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> res;
while(intervals.size() > ){
Interval inv = intervals.back();
intervals.pop_back();
vector<Interval>::iterator i = res.begin();
vector<Interval>::iterator rend = res.end();
for(; i < rend; ++i){
if(!((*i).start > inv.end || inv.start > (*i).end)){
(*i).start = min((*i).start, inv.start);
(*i).end = max((*i).end, inv.end);
intervals.push_back(*i);
res.erase(i);
break;
}
}
if(i == rend){ //事先将res.end()保存为rend很有必要,因为res.end()此时已经变化了。
res.push_back(inv);
}
}
return res;
}
};

AC 80ms

但上面的解法需要把一个Interval在两个vector间移来移去,而且每次从intervals取出后,又要从res的头部开始比较,比较费时间。最好当然是每次从intervals中取出一个Interval后,就将res中所有的都遍历完并合并。

这样的代码:

class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> res;
if(intervals.size() == ) return res;
for(vector<Interval>::iterator it = intervals.begin(); it != intervals.end(); ++it){
Interval* interval = new Interval(it -> start, it -> end);
for(vector<Interval>::iterator it2 = res.begin(); it2 < res.end();){
if(!(interval -> end < it2 -> start || it2 -> end < interval -> start)){
interval -> start = min(interval->start, it2->start);
interval -> end = max(interval->end, it2->end);
it2 = res.erase(it2);
}else ++it2;
}
res.push_back(*interval);
}
return res;
}
};

AC 56ms

上面两种解法都是新定义一个vector用来存放结果。如果不新定义vector直接在原intervals上操作呢?这种解法参考了tenos的解法

先将intervals按照start 升序排序,然后it1指向begin(),接着it2 指向it1的下一个元素,如果it2 和 it1有重叠,就把it2的区间算入 it1的区间,接着++it2,直到it2的区间和it1 没有重叠。

因为it2 走过的部分都已经被算入it1里,所以it1+1到当前it2的部分可以被删除了。

接着继续重复上述步骤,直到it1 或者 it2到达末尾。

这种解法要求 intervals 必须是有序的

class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
if(intervals.size() <= ) return intervals;
sort(intervals.begin(), intervals.end(), compare);
vector<Interval>::iterator it1 = intervals.begin();
vector<Interval>::iterator it2 = it1 + ;
while(it1 != intervals.end() && it2 != intervals.end()){
if(!(it2 -> end < it1 -> start || it1 -> end < it2 -> start)){
it1 -> start = min(it1 -> start, it2 -> start);
it1 -> end = max(it1 -> end, it2 -> end);
++it2;
}else{
it1 = intervals.erase(it1 + , it2);
it2 = it1 + ;
}
}
if((it1+) != it2) intervals.erase(it1 + , it2);
return intervals;
}
private:
static bool compare(Interval a, Interval b){
return (a.start < b.start);
}
};

AC 60ms 因为在原vector上操作,所以比起解法二 略慢了一些。

基于Merge,会衍生出一些题目,比如下面的Insert。

Insert Interval 

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是有序排列的,我们只要先将newInterval 放入 该放的地方,然后向后合并就可以。

class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval>::iterator it1 = intervals.begin();
for(; it1 != intervals.end() && it1 -> end < newInterval.start; ++it1); //放入该放的地方
it1 = intervals.insert(it1, newInterval);
vector<Interval>::iterator it2 = it1 + ;
for(; it2 != intervals.end(); ++it2){
if(!(it2 -> end < it1 -> start || it1 -> end < it2 -> start)){
it1 -> start = min(it1-> start, it2 -> start);
it1 -> end = max(it1 -> end, it2 -> end);
}else break; //如果it2不再和it1重叠,因为intervals有序排列,所以it2后面的Interval肯定也不和it1重叠,可以退出循环了。
}
if(it2 != (it1 + )) intervals.erase(it1+, it2); //删除it2走过的部分。
return intervals;
}
};

总结:

通过这两题,(1) 首先我们需要熟练掌握一个基本的判断两个Interval是否overlap的方法: if(!((*i).start > inv.end || inv.start > (*i).end))

(2) 使用vector 的iterator方法遍历时,如果遍历的同时存在vector的大小更改,需要特别注意大小更改对 .end() 结果的影响,最好先将.end() 保存下来,除非你确实需要 .end()的动态变化作为比较值。

(3) 若在遍历vector时使用erase或者insert,因为vector大小被更改,因此原来的iterator会失效,需要将iterator 赋值为erase 和 insert 的返回值。

erase返回的值为删除当前 iterator 指向的元素后,下一个元素所在的地址。

insert返回的值为新增元素所在的地址(仅限于insert 一个元素的情况)。

[LeetCode] Merge Interval系列,题:Insert Interval,Merge Intervals的更多相关文章

  1. 【Leetcode】【Hard】Insert Interval

    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa ...

  2. LeetCode第[21][23]题(Java):Merge Sorted Lists

    题目:合并两个已排序链表 难度:Easy 题目内容: Merge two sorted linked lists and return it as a new list. The new list s ...

  3. 【题解】【区间】【二分查找】【Leetcode】Insert Interval & Merge Intervals

    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa ...

  4. Leetcode: Merge/Insert Interval

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

  5. leetcode 56. Merge Intervals 、57. Insert Interval

    56. Merge Intervals是一个无序的,需要将整体合并:57. Insert Interval是一个本身有序的且已经合并好的,需要将新的插入进这个已经合并好的然后合并成新的. 56. Me ...

  6. leetcode 57 Insert Interval & leetcode 1046 Last Stone Weight & leetcode 1047 Remove All Adjacent Duplicates in String & leetcode 56 Merge Interval

    lc57 Insert Interval 仔细分析题目,发现我们只需要处理那些与插入interval重叠的interval即可,换句话说,那些end早于插入start以及start晚于插入end的in ...

  7. 【LeetCode】57. Insert Interval [Interval 系列]

    LeetCode中,有很多关于一组interval的问题.大体可分为两类: 1.查看是否有区间重叠: 2.合并重叠区间;  3.插入新的区间: 4. 基于interval的其他问题 [ 做题通用的关键 ...

  8. 合并区间 · Merge Intervals & 插入区间 · Insert Interval

    [抄题]: 给出若干闭合区间,合并所有重叠的部分. 给出的区间列表 => 合并后的区间列表: [ [ [1, 3], [1, 6], [2, 6], => [8, 10], [8, 10] ...

  9. 60. Insert Interval && Merge Intervals

    Insert Interval Given a set of non-overlapping intervals, insert a new interval into the intervals ( ...

随机推荐

  1. tendermint学习

    怎么把两个节点变成验证节点 1. 两个节点分别启动 2. 两个节点同时把自己的公钥信息添加到对方的创始快配置文件中,总而言之,创始块一样 3. unsafe_reset_priv_validator ...

  2. php面试全套

    7.mvc是什么?相互间有什么关系? 答:mvc是一种开发模式,主要分为三部分:m(model),也就是模型,负责数据的操作;v(view),也就是视图,负责前后台的显示;c(controller), ...

  3. 官方文档 恢复备份指南三 Recovery Manager Architecture

    本节讨论以下问题: About the RMAN Environment                        关于RMAN环境 RMAN Command-Line Client        ...

  4. 软件工程第四周作业之四则运算-C#实现

    拿到题目的时候,快放假了,也没心思做.十月七号的一下午大概从两点做到八点半,加上十月八号的十二点半到两点半,做了一共八个半小时,去掉吃饭半个小时那么一共做了八个小时. 逆波兰表达式我是扒的别人代码,没 ...

  5. poj 3009 (深搜求最短路)

    题目大意就是求在特定规则下的最短路,这个规则包含了消除障碍的操作.用BFS感觉选择消除障碍的时候不同路径会有影响,用DFS比较方便状态的还原(虽然效率比较低),因此这道题目采用DFS来写. 写的第一次 ...

  6. 【IdentityServer4文档】- 整体情况

    整体概况 大多数现代应用程序看起来或多或少像这样: 最常见的交互是: 浏览器与 Web 应用程序进行通信 Web 应用程序与 Web API 进行通信(有时是Web应用程序自己发起,有时代表用户发起) ...

  7. HashMap get()返回值问题

    问题描述:在进行mysql查询必要字段后,需要根据id进行es其它数据字段的查询拼接.使用HashMap以id为key 以查询过来的数据值为value. 代码如下: Map<String,Int ...

  8. iOS- <项目笔记>UI控件常见属性总结

    1.UIView // 如果userInteractionEnabled=NO,不能跟用户交互 @property(nonatomic,getter=isUserInteractionEnabled) ...

  9. Coredump及调试

    1.查看是否打开了coredump lybxin@Inspiron:~/MyRes/miscellany/test/01_coredump$ulimit -c  #这里可以看到ulimit限制core ...

  10. zookeeper伪集群安装

    记录下zookeeper伪分布式搭建的过程,假设系统已经配置好了JAVA环境. 1.准备环境 linux服务器一台,下载某个版本的zookeeper压缩包,下载链接:http://apache.cla ...