题目:

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:
static bool comp(Interval a, Interval b)
{
return a.start < b.start;
}
static vector<Interval> merge(vector<Interval>& intervals)
{
if (intervals.empty()) return intervals;
vector<Interval> ret;
std::sort(intervals.begin(), intervals.end(), Solution::comp);
int start = intervals[].start;
int end = intervals[].end;
for ( int i=; i<intervals.size(); ++i )
{
if ( intervals[i].start>end )
{
ret.push_back(Interval(start,end));
start = intervals[i].start;
end = intervals[i].end;
continue;
}
if ( intervals[i].start<=end )
{
start = std::min(start, intervals[i].start);
end = std::max(end, intervals[i].end);
continue;
}
}
ret.push_back(Interval(start,end));
return ret;
}
};

tips:

一开始理解题意有误,题中没说已经按照start对intervals排序了,所以先对intervals按照start排序(构造一个comp比较器)。接下来就是常规的思路了,每次判断当前interval的start end与之前start end的大小比较。

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

还有一种解法是沿用insert interval这道题的思路,每次新插入一个interval即可,代码如下.

/**
* 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> ret;
for ( int i=; i<intervals.size(); ++i )
{
ret = Solution::insert(ret, intervals[i]);
}
return ret;
}
static 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;
}
return ret;
}
};

tips:这相当于是对一个区间进行插入排序,之前做的都是针对数字进行插入排序。这道题考察的点还是很好的。

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

第二次过这道题,就是先按照start进行排序,再merge。

/**
* 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:
static bool compare(Interval a, Interval b)
{
return a.start < b.start;
}
vector<Interval> merge(vector<Interval>& intervals)
{
vector<Interval> ret;
if ( intervals.empty() ) return ret;
sort(intervals.begin(), intervals.end(), Solution::compare);
ret.push_back(*intervals.begin());
for ( vector<Interval>::iterator 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;
}
};

【Merge Intervals】cpp的更多相关文章

  1. 【Insert Interval】cpp

    题目: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if nec ...

  2. 【Reorder List】cpp

    题目: Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do ...

  3. hdu 4739【位运算】.cpp

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

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

  5. 【Multiply Strings】cpp

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

  6. 【Interleaving String】cpp

    题目: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given: ...

  7. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  8. 排序算法总结(二)归并排序【Merge Sort】

    一.归并排序原理(Wikipedia) 归并排序本质是分治思想的应用,并且各层分治递归可以同时进行 1.申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列 2.设定两个指针,最初位置 ...

  9. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

随机推荐

  1. ABAP Netweaver和Hybris Enterprise Commerce Platform的登录认证

    ABAP Netweaver 在我的博客Learn more detail about Standard logon procedure里有详细介绍. Hybris ECP Hybris Admini ...

  2. 启动Windows服务

    实现效果: 知识运用: ServiceController类的ServiceName Status属性 public string ServiceName {get; set;} //对此Servic ...

  3. .nettiers和SQLite搅合到一块之后遇到的问题

    第一步 用SQLiteStudio生成一个新的数据库,sqlitetest,新建一张表test,建立一个主键字段ID,一个字符字段Name,建立完成,留待后用. 第二步 用VS2010建立一个sqli ...

  4. pdo->prepare 返回false的问题总结

    报错信息: Fatal error: Call to a member function execute() on a non-object 一般是pdo->prepare 返回了false导致 ...

  5. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [spring/applicationContext-service.xml]: Cannot resolve refer

    <!-- aop --> <aop:config> <aop:pointcut expression="execution(* com.zsn.Service. ...

  6. Java连接数据库的一个问题

    问题描述: 利用HTML+servlet+MySQL写一个简单的登录注册案例,抛出了异常No suitable driver found for jdbc 解决方法 将mysql-connector- ...

  7. input属性总结

    <input type="text" readonly="readonly" /> 这个是不能输入的 readonly="readonly ...

  8. 从coding.net 克隆(git clone)项目代码到本地报无权限(403)错误 解决方案

    直接从coding.net (git clone)项目代码到本地时,会提示没有权限的错误,如下图: 解决方案:添加远程地址的时候带上用户名及密码即可解决,格式如下: git clone http:// ...

  9. linux 下chown改变隐藏文件夹

    chown 在更改隐藏文件的时候,发现无法更改其用户组,如果需要将隐藏文件夹也做一个更改,那么需要加上-h选项. sudo  chown ai/node/  * -hR 使用以上命令即可.

  10. C语言字符篇(二)字符串处理函数

    字符串处理函数 1. 拷贝 strcpy 2. 追加 strcat   #include <string.h>   char *strcpy(char *dest, const char ...