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

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

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].

Solution: 1. Sort in ascending order of 'start'.

2. Traverse the 'intervals', merge or push...

1 /** 2  * Definition for an interval. 3  * struct Interval { 4  *     int start; 5  *     int end; 6  *     Interval() : start(0), end(0) {} 7  *     Interval(int s, int e) : start(s), end(e) {} 8  * }; 9  */10 11 bool compare(const Interval &a, const Interval &b) 12 {13     return a.start < b. start;14 }15 class Solution {16 public:17     18     vector
merge(vector
&intervals) {19 vector
res;20 int N = intervals.size(); 21 if(N <= 1) return intervals;22 sort(intervals.begin(), intervals.end(), compare);23 Interval last = intervals[0];24 for(int i = 1; i < N; i++) {25 if(intervals[i].start > last.end) {26 res.push_back(last);27 last = intervals[i];28 }29 else {30 last.end = max(last.end, intervals[i].end);31 }32 }33 res.push_back(last);34 return res;35 }36 };

 

转载于:https://www.cnblogs.com/zhengjiankang/p/3667811.html

你可能感兴趣的文章
Java中的逆变与协变
查看>>
ASP.NET站点
查看>>
mvc
查看>>
[leetcode]Map-560. Subarray Sum Equals K
查看>>
LeetCode No.6 ZigZag Conversion
查看>>
CSS中position为relative时的特性
查看>>
javascript类式继承最优版
查看>>
opencv
查看>>
将相关数据拼成所需JSON数据
查看>>
第一章
查看>>
python全栈-Day 13
查看>>
二十五、侧边栏(charm)
查看>>
C# 部分类: partial关键字的作用(转摘)
查看>>
Bootstrap基础(七):按钮
查看>>
CPoint、CSize、CRect类
查看>>
tftp服务器的搭建和使用
查看>>
python学习01
查看>>
PostgreSQL的case when
查看>>
(转载)虚幻引擎3--【UnrealScript教程】章节一:4.代码的注释
查看>>
如何阅读他人的程序代码
查看>>