This is a place to put my clutters, no matter you like it or not, welcome here.
0%
56. Merge Intervals
Posted onIn面試Views: Symbols count in article: 989Reading time ≈1 mins.
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
1 2 3
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] overlaps, merge them into [1,6].
Example 2:
1 2 3
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
先用第一個值排序,再取第二個值比較多的部份。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# T: O(nlogn), S: O(n) class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: # sort the intervals by their start value intervals.sort(key=lambda x: x[0])
merged = [] for interval in intervals: # if the list of merged intervals is empty or if the current # interval does not overlap with the previous, simply append it. if not merged or merged[-1][1] < interval[0]: merged.append(interval) else: # otherwise, there is overlap, so we merge the current and previous intervals. merged[-1][1] = max(merged[-1][1], interval[1])