Google面试题专题8 - leetcode57. Insert Interval

57. Insert Interval - Mark

题目描述

给定无重叠区间的列表,在列表中插入新区间。

假设初始时区间已经根据start排好序。

例子
Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]

Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

思想
肯定需要遍历一遍intervals,所以时间复杂度至少O(n)。
要点:找到哪些区间有可能和newInterval重合,把这些区间合并,并加上它左右的区间即可。
解法
时间复杂度O(n)

# 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]
        """
        start, end = newInterval.start, newInterval.end
        left, right = [], []
        for interval in intervals:
            if interval.end < start:
                left.append(interval)
            elif interval.start > end:
                right.append(interval)
        # overlapping
        if len(left) + len(right) != len(intervals):
            start = min(start, intervals[len(left)].start)
            end = max(end, intervals[-len(right)-1].end)
        
        return left + [Interval(start, end)] + right

你可能感兴趣的:(Leetcode)