您的位置:首页 > 其它

[Leetcode 84] 56 Merge Intervals

2013-07-24 13:13 375 查看
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:

/**
* Definition for an interval.
* struct Interval {
*     int start;
*     int end;
*     Interval() : start(0), end(0) {}
*     Interval(int s, int e) : start(s), end(e) {}
* };
*/

bool cmpA(const Interval& a, const Interval& b)
{
return a.start < b.start;
}

class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
// Start typing your C/C++ solution below
// DO NOT write int main()
vector<Interval> res;
sort(intervals.begin(), intervals.end(), cmpA);

Interval tmp = intervals[0];
for (int i=1; i<intervals.size(); i++) {
if (tmp.start <= intervals[i].start &&
tmp.end >= intervals[i].start) {
tmp.end = max(intervals[i].end, tmp.end);
}
else {
res.push_back(tmp);
tmp = intervals[i];
}
}

return res;
}

int max(int a, int b) {
return (a>b)? a : b;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: