题目来源:
https://leetcode.com/problems/insert-interval/
题意分析:
给定一个互相没交叉排好序的间隔,再给一个新的间隔,将这个间隔和原来的间隔串整合成新的间隔串。
题目思路:
首先将新的间隔插入原来的间隔串。然后整合。
代码(python):
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ def find(intervals,newInterval): size = len(intervals) if size == 0: return 0 first,last = 0,size while first < last: mid = (first + last) // 2 if intervals[mid].start == newInterval.start: return mid elif intervals[mid].start < newInterval.start: first = mid + 1 else: last = mid return max(0,first) intervals.insert(find(intervals,newInterval),newInterval) ans,size = [],len(intervals) tmp = intervals[0] for i in intervals: if i.start <= tmp.end: tmp.end = max(i.end,tmp.end) else: ans.append(tmp) tmp = i ans.append(tmp) return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/4969196.html