LeetCode 56. 合併區間
阿新 • • 發佈:2018-12-18
給出一個區間的集合,請合併所有重疊的區間。
示例 1:
輸入: [[1,3],[2,6],[8,10],[15,18]] 輸出: [[1,6],[8,10],[15,18]] 解釋: 區間 [1,3] 和 [2,6] 重疊, 將它們合併為 [1,6].
示例 2:
輸入: [[1,4],[4,5]] 輸出: [[1,5]] 解釋: 區間 [1,4] 和 [4,5] 可被視為重疊區間。
渣渣晴寫的太蠢了
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ i=0 while i<len(intervals)-1: j=i+1 while j<len(intervals): if intervals[i].start<=intervals[j].start and intervals[i].end>=intervals[j].end:#i包括j del intervals[j] elif intervals[j].start<=intervals[i].start and intervals[j].end>=intervals[i].end:#j包括i intervals[i].end=intervals[j].end intervals[i].start=intervals[j].start del intervals[j] j=i+1 elif intervals[i].end>=intervals[j].start and intervals[i].start<=intervals[j].end and intervals[i].start<=intervals[j].start:#i尾j頭拼接 intervals[i].end=intervals[j].end del intervals[j] j=i+1 elif intervals[j].end>=intervals[i].start and intervals[j].start<=intervals[i].end and intervals[j].start<=intervals[i].start:#j尾i頭拼接 intervals[i].start=intervals[j].start del intervals[j] j=i+1 else: j=j+1 i=i+1 return intervals
大佬的程式碼:
先按start排個序……再看看能不能合併……
class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals.sort(key=lambda x :x.start) result = [] for item in intervals: if not result or result[-1].end < item.start: result.append(item) else: result[-1].end = max(item.end, result[-1].end) # print(result) return result