56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input:
[[1,3],[2,6],[8,10],[15,18]]
Output:
[[1,6],[8,10],[15,18]]
Explanation:
Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input:
[[1,4],[4,5]]
Output:
[[1,5]]
Explanation:
Intervals [1,4] and [4,5] are considered overlapping.
Thoughts:
- Sort the interval list according the start point
- record end, for loop check whether the current interval's start time is after the record end; if it is, merge the interval by maxing the end time; if it is not, insert the interval of recorded start and end time and update them to start another interval to be merged with current start and end time.
Code Java O(nlogn): Java8 lambda comparator
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if(intervals.size() <= 1) return intervals;
intervals.sort((i1, i2)->Integer.compare(i1.start, i2.start)); // java8 lambda
int start = intervals.get(0).start, end =intervals.get(0).end;
List<Interval> results = new LinkedList <Interval>();
for(Interval i: intervals){
if(i.start <= end){
end = Math.max(i.end, end); // merging
}
else{
results.add(new Interval(start, end)); // disjoint: first adding existing merged intervals, then update start, end
start = i.start; end = i.end; // update start, end
}
}
results.add(new Interval(start, end));
return results;
}
}
Code 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]
"""
intervals =sorted(intervals, key=lambda x:x.start)
results = []
l = len(intervals)
i = 0
while i < l:
s = intervals[i].start
e = intervals[i].end
j = i + 1
while j < l and e >= intervals[j].start:
e = max(e, intervals[j].end)
j += 1
results.append(Interval(s,e))
i = j
return results