56. Merge Intervals
Problem description:
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.
Solution:
- First of all, we can sort the array of intervals by its start value. The sort can use lambda function.
- After we sort the array, we can easily found out that the only condition we need to check is whether if
i
‘s end value is smaller thani+1
‘s start value.
For example:
original: [[4,3],[2,6],[3,5],[7,18]]
sorted: [[2,6],[3,5],[4,7],[8,18]]
- init round: push the
[2,6]
into result. - 1st round:
compare[2,6]
and[3,5]
.6
is greater than3
, so we then compare end value from both range. - 2nd round:
compare[2,6]
and[4,7]
. update[2,6]
to[2,7]
- 3rd round:
compare[2,7]
and[8,18]
. Since8
is greater than7
, it can not merge together, so we push[8,18]
into the result.
1 | /** |
reference: