LeetCode OJ:Merge Intervals(合并区间)
2016-01-12 22:37
246 查看
Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
看起来感觉不像hard类型的题目,不过要注意的一点是这里给出的数据不一定会像上面这样按照顺序来进行排序,所以处理前首先要按照一定的规则处理一下,写一个functor来进行比较,用struct即可,排序后这个范围就很好确定了,代码如下所示:
For example,
Given
[1,3],[2,6],[8,10],[15,18],
return
[1,6],[8,10],[15,18].
看起来感觉不像hard类型的题目,不过要注意的一点是这里给出的数据不一定会像上面这样按照顺序来进行排序,所以处理前首先要按照一定的规则处理一下,写一个functor来进行比较,用struct即可,排序后这个范围就很好确定了,代码如下所示:
class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { int p = 0, q = 1; std::sort(intervals.begin(), intervals.end(), comp); vector<Interval> ret; while(q < intervals.size()){ if(intervals[p].end < intervals[q].start){ //这个范围需要记录下来 ret.push_back(intervals[p]); p = q; q++; }else{ if(intervals[p].end < intervals[q].end) //根据条件才更新范围 intervals[p].end = intervals[q].end; q++; } } if(p < intervals.size()) ret.push_back(intervals[p]); return ret; } struct myComparator{ bool operator()(const Interval & i, const Interval & j){ return i.start < j.start; } }comp; };
相关文章推荐
- switch 语句:error : crosses initialization of 'xxx' and jump to case label [-fpermissive]
- HDU 1597:find the nth digit【规律】
- mysql存储过程事务处理小经验
- 打包成Jar后相对路径的获取
- 【工具优化】Eclipse设置(包括优化、易用性、必备插件等的说明)----持续更新
- python核心编程-正则表达式之-创建字符集合
- s_ 01字串
- MySQL ERROR 1045 (28000): Access denied for user解决方法
- jenkins + Git 搭建持续集成环境
- 程序员「奇葩」说
- 解决SecureCRT连接linux超时后断开
- 【学神-RHEL7】P4-Python列表操作和字符串的常用方法
- iOS 语音
- 程序员「奇葩」说
- 程序员「奇葩」说
- shell中的括号(小括号,中括号,大括号/花括号)
- Block的应用场景
- 程序员「奇葩」说
- 实现应用Matrix缩放图像
- 应用 EditPlus 配置 Java 编译环境