您的位置:首页 > 其它

leetcode 56:Merge Intervals

2015-11-18 19:27 381 查看
题目:

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]
.
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};


思路:
可以先对集合进行排序,时间复杂度:O(nlgn)

然后依次将end大于下一个start的集合合起来,知道出现end小于下一个start,将新的集合push到结果中。

注意边界条件,即下一个集合是前一个的子集的情况。时间复杂度:O(n)

总时间复杂度为:O(nlgn)

实现如下:

class Solution {
public:
static bool comp(const Interval a, const Interval b)
{
return a.start < b.start ? 1 : 0;
}
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
int size = intervals.size();
if (size < 2) return intervals;
sort(intervals.begin(), intervals.end(), comp);
for (int i = 0; i<size; ++i)
{
Interval temp(intervals[i].start, intervals[i].end);
int high = intervals[i].end;
while (i < size - 1 && high >= intervals[i + 1].start)
{
if (intervals[i + 1].end > high) high = intervals[i + 1].end;
++i;
}
temp.end = high;
result.push_back(temp);
}
return result;
}
};


注意:本题对sort的使用。由于sort第三个参数对应函数的地址,如果函数不加上static,则会报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: