题目:
给出一个区间的集合, 请合并所有重叠的区间。(源自:LeeCode题库)
示例:
给出 [1,3],[2,6],[8,10],[15,18],
给出一个区间的集合, 请合并所有重叠的区间。(源自:LeeCode题库)
示例:
给出 [1,3],[2,6],[8,10],[15,18],
返回 [1,6],[8,10],[15,18].
思路:首先新建一个类Interval 用来保存区间 形如【1,3】
其次对给出集合的下限进行排序 按照升序排列 (这里选择较为简单的冒泡排序)
合并区间。这里要注意的就是条件的选择,何时将两个区间合并为一个区间,何时又跳过考虑下一个。最后将合并好的区间输出。
代码如下:
#exercise 1 #first new one class to store intervals just like (1,3) class Interval(object): def __init__(self,s=0,e=0): self.start = s self.end = e #second new one class to solve the question class Solution(object): #first new one method to bubble the intervals def bubbles(self,intervals): for i in range(0,len(intervals)): for j in range(i+1,len(intervals)): if intervals[i].start > intervals[j].start: intervals[i],intervals[j] = intervals[j],intervals[i] return intervals #second merge intervals , print result def merge(self,intervals): if len(intervals) > 0: global start global end result = [] #used to store result result_mark = 0 intervals = self.bubbles(intervals) #sort result.append([intervals[0].start,intervals[0].end]) while True: if (result[result_mark][1] >= intervals[0].start) and (result[result_mark][1] <= intervals[0].end): result[result_mark][1] = intervals[0].end intervals.pop(0) if len(intervals) == 0: break elif(result[result_mark][0] <= intervals[0].start) and (result[result_mark][1] >= intervals[0].end): intervals.pop(0) if len(intervals) == 0: break else: result.append([intervals[0].start,intervals[0].end]) result_mark += 1 intervals.pop(0) if len(intervals) == 0: # not need break return result else: return [] solution = Solution() print(solution.merge([Interval(1,5),Interval(1,2),Interval(11,20)]))