56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[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:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
解题思路:
题意很明确,首先对各区间按开始来排序(选用了快速排序),最后遍历,如果前面和后面的区间有重合(分三种情况讨论),合并。
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
# index = 0
self.quicksort(intervals, 0,len(intervals)-1)
result = []
# print(intervals)
for i in range(len(intervals)):
if i < len(intervals)-1 and intervals[i][1] >= intervals[i+1][0] and intervals[i][1] <= intervals[i+1][1]:
# print(intervals[i+1][0],intervals[i][0])
intervals[i+1][0] = intervals[i][0]
# index += 1
elif i < len(intervals)-1 and intervals[i][1] >= intervals[i+1][0] and intervals[i][1] > intervals[i+1][1]:
intervals[i+1][0] = intervals[i][0]
intervals[i+1][1] = intervals[i][1]
# index += 1
else:
result.append(intervals[i])
# print(intervals)
return result
def quicksort(self,nums,l,h):
if l < h:
pivotpos = self.partition(nums,l,h)
self.quicksort(nums,l,pivotpos - 1)
self.quicksort(nums,pivotpos + 1,h)
def partition(self,nums,l,h):
p = nums[l]
while l < h:
while l < h and nums[h][0] >= p[0]:
h -= 1
nums[l] = nums[h]
while l < h and nums[l][0] <= p[0]:
l += 1
nums[h] = nums[l]
nums[l] = p
return l
请多多指教。
文章标题:56. Merge Intervals
本文作者:顺强
发布时间:2019-09-02, 23:59:00
原始链接:http://shunqiang.ml/leetcode-56-merge-intervals/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。