题目

【leetcode/python3/hard/57】Insert Interval

基本思路

首先,将newInterval添加到intervals中,然后按照区间开始数值,进行排序,最后将对于是否需要merge进行判断,分情况处理

花费了额外的存储空间

实现代码

# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        intervals.append(newInterval)
        intervals.sort(key=lambda x:x.start)
        length = len(intervals)
        
        res = []
        
        for i in range(length):
            if res == []:
                res.append(intervals[i])
            else:
                if res[-1].start <= intervals[i].start <= res[-1].end:
                    res[-1].end = max(intervals[i].end,res[-1].end)
                else:
                    res.append(intervals[i])
        return res
            
        

相关文章:

  • 2022-02-08
  • 2022-01-16
  • 2021-11-23
  • 2022-12-23
  • 2021-10-30
  • 2020-04-22
  • 2021-09-28
  • 2022-03-10
猜你喜欢
  • 2022-01-25
  • 2021-07-28
  • 2021-09-23
  • 2021-10-06
  • 2022-02-11
相关资源
相似解决方案