标签:leetcode algorithm sort merge c++
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]
.
这个题目其实不难,只要理清楚各种情况利用插入排序的方法就可以完成,我的C++代码实现如下:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> mergeIntervals;
for (auto interval : intervals) {
int i;
for (i = 0; i < mergeIntervals.size(); ++i) {
if (interval.end < mergeIntervals[i].start) {
mergeIntervals.insert(mergeIntervals.begin() + i, interval);
break;
}
else if (interval.start <= mergeIntervals[i].end) {
mergeIntervals[i].start = min(interval.start, mergeIntervals[i].start);
if (interval.end > mergeIntervals[i].end) {
while (i + 1 < mergeIntervals.size() && interval.end >= mergeIntervals[i + 1].start) {
mergeIntervals[i].end = mergeIntervals[i + 1].end;
mergeIntervals.erase(mergeIntervals.begin() + i + 1);
}
mergeIntervals[i].end = max(interval.end, mergeIntervals[i].end);
}
break;
}
}
if (i == mergeIntervals.size())
mergeIntervals.push_back(interval);
}
return mergeIntervals;
}
时间性能表现如下图所示:
另外,在Discuss上看到这样一种解法(https://oj.leetcode.com/discuss/13953/a-simple-java-solution):首先利用sort函数将所有输入的intervals按照start排序,然后再挨个儿插入。这个方法也值得借鉴。
LeetCode[Sort]: Merge Intervals
标签:leetcode algorithm sort merge c++
原文地址:http://blog.csdn.net/chfe007/article/details/43486947