[Leetcode 84] 56 Merge Intervals

合并区间问题详解
本文详细介绍了如何解决合并区间的问题,并提供了一种有效的算法实现。首先对区间进行排序,然后遍历每个区间,若当前区间的开始时间在前一区间的结束时间内,则合并这两个区间;否则将前一区间加入结果集。此方法提高了处理效率。

Problem:

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

 

Analysis:

First sort the vector according to the start time of each interval. Then scan through the vector, if the current interval's start time is between the former interval's strart and end time, we need to merge them. The newly merged interval's start is the former interval's start, but the end should be the max{current.end, former.end}.

To speed up this process, use an extra result vector to store the final result rather than using vector.erase method on original method.

 

Code:

 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 cmpA(const Interval& a, const Interval& b)
12 {
13     return a.start < b.start;
14 }
15 
16 class Solution {
17 public:
18     vector<Interval> merge(vector<Interval> &intervals) {
19         // Start typing your C/C++ solution below
20         // DO NOT write int main() 
21         vector<Interval> res;
22         sort(intervals.begin(), intervals.end(), cmpA);
23 
24         Interval tmp = intervals[0];
25         for (int i=1; i<intervals.size(); i++) {
26             if (tmp.start <= intervals[i].start &&
27                 tmp.end >= intervals[i].start) {
28                     tmp.end = max(intervals[i].end, tmp.end);
29             }
30             else {
31                 res.push_back(tmp);
32                 tmp = intervals[i];
33             }
34         }
35 
36         return res;
37     }
38     
39     int max(int a, int b) {
40         return (a>b)? a : b;
41     }
42 };
View Code

 

转载于:https://www.cnblogs.com/freeneng/p/3210450.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值