Merge Intervals
问题描述:
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].
知识补充:
自定义sort函数
sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;});
测试代码(c++):
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if(intervals.size()<=1)
return intervals;
sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){return a.start < b.start;});
int left = intervals[0].start;
int right = intervals[0].end;
for(int i=1;i<intervals.size();i++)
{
if(intervals[i].start>right||intervals[i].end<left)
{
result.push_back(intervals[i-1]);
left = intervals[i].start;
right = intervals[i].end;
}
intervals[i].start = min(intervals[i].start,left);
intervals[i].end = max(intervals[i].end,right);
left = intervals[i].start;
right = intervals[i].end;
}
result.push_back(intervals.back());
return result;
}
};
性能:
测试代码(python):
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
out = []
for i in sorted(intervals, key=lambda i: i.start):
if out and i.start <= out[-1].end:
out[-1].end = max(out[-1].end, i.end)
else:
out += i,
return out