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. LeetCode - 463. Island Perimeter - O(MN)- (C++) - 解题报告

    原题 原题链接 You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 ...

  2. JQuery文本框验证

    <" CODEPAGE="936"%><!--#include file="conncon.asp"--><!--#in ...

  3. 一:yarn 介绍

        yarn的了出现主要是为了拆分jobtracker的两个核心功能:资源管理和任务监控,分别对应resouceManager(RM)和applicationManager(AM).yarn中的任 ...

  4. 【转】redis安装与配置

    一.安装 1.官方:http://www.redis.cn/download.html 2.下载.解压.编译 wget http://download.redis.io/releases/redis- ...

  5. vue学习笔记之:为何data是一个方法

    vue学习笔记之:为何data是一个方法 在vue开发中,我们可以发现,data中的属性值是在function中return出来的.可为何data必须是一个函数呢?我们先看官方的解释: 当一个组件被定 ...

  6. 并查集(Union/Find)模板及详解

    概念: 并查集是一种非常精巧而实用的数据结构,它主要用于处理一些不相交集合的合并问题.一些常见的用途有求连通子图.求最小生成树的Kruskal 算法和求最近公共祖先等. 操作: 并查集的基本操作有两个 ...

  7. "Hello world!"团队第一次会议

    今天是我们"Hello world!"团队第一次召开会议,今天的会议可能没有那么正式,但是我们一起确立了选题——基于WEB的售票系统.博客内容是: 1.会议时间 2.会议成员 3. ...

  8. Thunder团队Beta周贡献分规则

    小组名称:Thunder 项目名称:i阅app 组长:王航 成员:李传康.翟宇豪.邹双黛.苗威.宋雨.胡佑蓉.杨梓瑞 分配规则 规则1:基础分,拿出总分的20%(8分)进行均分,剩下的80%(32分) ...

  9. 软件工程课堂作业(二)续——升级完整版随机产生四则运算题目(C++)

    一.设计思想: 1.根据题目新设要求,我将它们分为两类:一类是用户输入数目,根据这个数目改变一系列后续问题:另一类是用户输入0或1,分情况解决问题. 2.针对这两类要求,具体设计思路已在上篇博文中写出 ...

  10. Win10修改编辑hosts文件无法保存怎么办

    Win10无法修改编辑保存hosts文件怎么办?Win10系统默认是没有权限去编辑保存系统里的文件,这也是权限不够才导致修改编辑hosts后无法保存的原因,解决的办法就是把自己的帐户权限给提高就行了. ...