博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Merge Intervals
阅读量:6316 次
发布时间:2019-06-22

本文共 2431 字,大约阅读时间需要 8 分钟。

The idea to solve this problem is to first sort the intervals according to their start field and then scan the intervals from head to tail and merge those that overlap.

For sorting the intervals according to their start field, we define a comparison function as follows.

1 static bool comp(Interval interval1, Interval interval2) {2     return interval1.start < interval2.start;3 }

Then all the intervals are sorted in the ascending order of start. Now we define a current intervalcur and initialize it to be intervals[0]. Then we scan from intervals[1] to intervals[n - 1]. If it overlaps with cur, merge them; otherwise, add cur to res, update cur to be intervals[i]and move on with the merging process.

There are two required subroutines in the above process: isOverlap to tell whether two intervals overlap and mergeTwo to merge two overlapping intervals.

For isOverlap, since the intervals are sorted in ascending order of start, we simply need to guarantee that end of the left (with smaller start) interval is not less than start of the right (with larger start) interval.

For mergeTwo, just take the minimum of start and maximum of end of the two overlapping intervals and return a new interval with these two values.

The complete code is as follows, which should be self-explanatory.

1 class Solution { 2 public: 3     vector
merge(vector
& intervals) { 4 vector
res; 5 if (intervals.empty()) return res; 6 sort(intervals.begin(), intervals.end(), comp); 7 Interval cur(intervals[0].start, intervals[0].end); 8 for (int i = 1, n = intervals.size(); i < n; i++) { 9 if (isOverlap(cur, intervals[i]))10 cur = mergeTwo(cur, intervals[i]);11 else {12 res.push_back(cur);13 cur = intervals[i];14 }15 }16 res.push_back(cur);17 return res;18 }19 private:20 static bool comp(Interval interval1, Interval interval2) { 21 return interval1.start < interval2.start;22 }23 bool isOverlap(Interval interval1, Interval interval2) {24 return interval1.end >= interval2.start;25 }26 Interval mergeTwo(Interval interval1, Interval interval2) {27 int start = min(interval1.start, interval2.start);28 int end = max(interval1.end, interval2.end);29 return Interval(start, end);30 }31 };

 

转载地址:http://jmuaa.baihongyu.com/

你可能感兴趣的文章
oracle数据泵导入分区表统计信息报错(四)
查看>>
spring技术内幕读书笔记之IoC容器的学习
查看>>
细说多线程(五) —— CLR线程池的I/O线程
查看>>
Hadoop文件系统详解-----(一)
查看>>
我的友情链接
查看>>
多年一直想完善的自由行政审批流程组件【2002年PHP,2008年.NET,2010年完善数据设计、代码实现】...
查看>>
自动生成四则运算题目
查看>>
数据库设计中的14个技巧
查看>>
Android学习系列(5)--App布局初探之简单模型
查看>>
git回退到某个历史版本
查看>>
ecshop
查看>>
HTML5基础(二)
查看>>
在Mac 系统下进行文件的显示和隐藏
查看>>
ue4(c++) 按钮中的文字居中的问题
查看>>
技能点
查看>>
读书笔记《乌合之众》
查看>>
Hadoop日记Day1---Hadoop介绍
查看>>
centos7 yum安装jdk
查看>>
zzzzw_在线考试系统①准备篇
查看>>
剑指offer第二版-1.赋值运算符函数
查看>>