給出多個數據區段,把首尾相連的數據段合並。
注意點:
所給的數據段是亂序的例子:
輸入: intervals = [1,3],[2,6],[8,10],[15,18]
輸出: [1,6],[8,10],[15,18]
先把所有的數據段按照起始位置(start)排序,這樣可以使可能相連的數據段到放到相鄰的位置。遍歷數據段,並與結果集中最後一個數據段比較能否合並,如果能合並就合並,否則加入結果集。
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
# To print the result
def __str__(self):
return "[" + str(self.start) + "," + str(self.end) + "]"
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
result = []
if not intervals:
return result
intervals.sort(key=lambda x: x.start)
result.append(intervals[0])
for interval in intervals[1:]:
prev = result[-1]
if prev.end >= interval.start:
prev.end = max(prev.end, interval.end)
else:
result.append(interval)
return result
if __name__ == "__main__":
intervals = Solution().merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)])
for interval in intervals:
print(interval)