In the "LeetCode" problem series, one of the popular questions is about merging intervals. This problem is a classic example of interval manipulation and can be solved using various strategies.
Problem Description
Given a collection of intervals, merge all overlapping intervals.
Example:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Solution Strategy
The most common approach to solve this problem is to:
- Sort the intervals based on their start times.
- Iterate through the sorted intervals and merge them if they overlap.
Implementation
Here's a simple implementation in Python:
def merge(intervals):
if not intervals:
return []
# Step 1: Sort the intervals based on the start time
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
previous = merged[-1]
# Check if there is an overlap
if previous[1] >= current[0]:
# Merge the intervals
previous[1] = max(previous[1], current[1])
else:
# No overlap, add the current interval to the result
merged.append(current)
return merged
Further Reading
To learn more about interval manipulation and the problems related to it, you can check out the following resources:
图片展示:
代码示例:
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
previous = merged[-1]
if previous[1] >= current[0]:
previous[1] = max(previous[1], current[1])
else:
merged.append(current)
return merged
希望这个例子能够帮助你更好地理解合并区间的问题。