leetcode中有幾道和數字區間合並有關的題,大致就是有交集的地方,把這幾個有交集的區間合並起來。
思路如下:
先將所有區間按照開頭進行排序,然后開始遍歷,用目前已確定的區間的尾部 和 即將要判斷的區間的頭部 比較大小,
1)如果尾部>=頭部,證明有交集,就去看這兩個區間誰的尾部更大,取更大的尾部;
2)如果尾部<頭部,證明沒有交集,那么直接把這個已確定的區間放入返回結果中,然后繼續判斷。
以Leetcode56題為例:
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) == 0: return []
intervals = sorted(intervals, key = lambda x: x.start) # 根據每個小list的第一個值進行遞增排序
res = [intervals[0]]
for n in intervals[1:]:
if n.start <= res[-1].end: res[-1].end = max(n.end, res[-1].end) # 第二個的開始小於res中最大區間的尾部(用-1找到)(證明兩者有交集,然后尾部取這兩個交集尾部的較大值)
else: res.append(n) # 如果第二個區間的小值比res中最大區間的尾部還大(證明沒有交集)
return res
