The solution involves sorting the list of intervals based on the start time of each interval to ensure that any potentially overlapping intervals are next to each other. After sorting, the algorithm initializes the first interval as the current range to merge other intervals into. For each subsequent interval, it checks if there is an overlap with the current range (i.e., the start of the next interval is less than or equal to the end of the current interval). If they overlap, the end of the current merged interval is updated if necessary. If there is no overlap, the current merged interval is complete and added to the results list, and a new current interval is started with the non-overlapping interval. This process is repeated for all intervals. Finally, the last merged interval is added to the results list.
时间复杂度: O(n log n)
空间复杂度: O(n)
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# Check if there's only one interval, return it directly
n = len(intervals)
if n == 1: return intervals
# Sort intervals based on the start of each interval
intervals.sort(key=lambda x: x[0])
ans = []
begin, end = intervals[0]
# Iterate through each interval to merge
for i in range(1, n):
a, b = intervals[i]
if a <= end:
# There is an overlap, so merge the intervals
if b > end: end = b
else:
# No overlap, add the current interval to the answer
ans.append([begin, end])
begin, end = a, b
# Add the last processed interval to the list
ans.append([begin, end])
return ans