返回
挑战LeetCode 56:使用Python巧妙解决合并区间问题
前端
2024-02-07 15:10:03
问题陈述
LeetCode 56:合并区间
给定一个包含闭合区间列表intervals
,每个列表项都表示一个区间。合并所有重叠的区间,并以按区间起始端点排序后的形式返回合并后的区间。
例如:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, we can merge them to [1,6].
Python解决方案
def merge_intervals(intervals):
"""
Merges overlapping intervals in a list.
Args:
intervals (list): A list of intervals, where each interval is a list of two integers representing the start and end points of the interval.
Returns:
list: A list of merged intervals.
"""
# Sort the intervals by their start points.
intervals.sort(key=lambda x: x[0])
# Initialize the merged_intervals list.
merged_intervals = []
# Iterate over the sorted intervals.
for interval in intervals:
# If the merged_intervals list is empty, or if the current interval does not overlap with the previous interval, add the current interval to the merged_intervals list.
if not merged_intervals or interval[0] > merged_intervals[-1][1]:
merged_intervals.append(interval)
# Otherwise, merge the current interval with the previous interval.
else:
merged_intervals[-1][1] = max(merged_intervals[-1][1], interval[1])
# Return the merged_intervals list.
return merged_intervals
复杂度分析
- 时间复杂度:
O(n log n)
,其中n
是区间列表中的区间数。 - 空间复杂度:
O(n)
,其中n
是区间列表中的区间数。
总结
在本篇博文中,我们探索了如何巧妙地解决LeetCode 56:合并区间的问题。我们提供了详细的Python代码实现并对其进行了复杂度分析。我们还讨论了适用于多种数组类型问题的解决思路,供您在LeetCode之旅中参考。我们鼓励您尝试使用本文介绍的技巧解决更多LeetCode难题,并不断提升您的编程能力。