Merge Intervals
Source
Given a collection of intervals, merge all overlapping intervals.
Example
Given intervals => merged intervals:
[ [
[1, 3], [1, 6],
[2, 6], => [8, 10],
[8, 10], [15, 18]
[15, 18] ]
]
Challenge
O(n log n) time and O(1) extra space.
Python
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
def merge(self, intervals):
result=[]
if intervals is None or len(intervals)==0:
return result
intervals = sorted(intervals, key=lambda tup: tup.start)
pre = intervals[0]
for interval in intervals:
if pre.end<interval.start:
result.append(pre)
pre=interval
else:
pre.end = max(pre.end, interval.end)
result.append(pre)
return result
Java
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if(intervals==null || intervals.size()==0){
return intervals;
}
List<Interval> result = new ArrayList<Interval>();
Collections.sort(intervals, new Comparator<Interval>(){
public int compare(Interval l1, Interval l2){
return l1.start-l2.start;
}
});
Interval pre = intervals.get(0);
for(int i=1; i<intervals.size(); i++){
Interval interval = intervals.get(i);
if(pre.end<interval.start){
result.add(pre);
pre=interval;
}
else{
pre.end=Math.max(pre.end, interval.end);
}
}
result.add(pre);
return result;
}
}