56. Merge Intervals
I solved this problem using C++.
My idea: sort the intervals by their first element, then merge the intervals.
1 | class Solution |
It’s like recursive merge sort.
Merge current interval as new current interval, the next interval is same as the current interval.
If the next interval is not overlapping with the current interval, push the current interval to the merged intervals and set the next interval as the new current interval.
Finally, push the last current interval to the merged intervals.
e.g.
intervals = [[2,3],[4,5],[6,7],[8,9],[1,10]]
sort intervals = [[1,10],[2,3],[4,5],[6,7],[8,9]]
merged = []
currentInterval = [1,10]
if currentInterval[1] >= intervals[1][0] && currentInterval[0] <= intervals[1][1]:
update currentInterval with new up and down bound
e.g.
intervals = [[1,3],[2,6],[8,10],[15,18]]
sort intervals = [[1,3],[2,6],[8,10],[15,18]]
merged = []
currentInterval = [1,3]
from [1, 3]
to [2, 6]
:
currentInterval => [1, 6]
[8, 10]
is not overlapping with [1, 6]
, so push [1, 6]
to merged intervals
now currentInterval = [8, 10]
…
finally push the last currentInterval to merged intervals
conclusion
It’s a simple problem…