56_57. 合并插入区间

复制代码
56. 合并区间

->用sort()函数排序:按a[0],a[1]大小排序
  判断区间重叠:eg- a=[1,4] b=[2,3]
                       a[1]>b[0]
                       左边位置为a[0],右边位置为max(a[1],b[1])
                       所以区间是[1,4]
-<代码:
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort()
        res = [intervals[0]]
        for x,y in intervals[1:]:
            if res[-1][1]<x:
                res.append([x,y])
            else:
                res[-1][1]=max(y,res[-1][1])
        return res
复制代码

 

复制代码
#双指针解法
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort()   #排序列表,以区间开头升序排列
        ans = [intervals[0]]
        L, R = 1, 0
        while L < len(intervals):
            if ans[R][1] < intervals[L][0]:   #如果区间不重合,直接append
                ans.append(intervals[L])
                L += 1
                R += 1
            else:      #如果区间重合,就合并区间
                ans[R] = [ans[R][0], max(ans[R][1], intervals[L][1])]
                L += 1
        return ans
复制代码
复制代码
57. 插入区间
class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        intervals.append(newInterval)
        intervals.sort()
        res = [intervals[0]]
        for x,y in intervals[1:]:
            if res[-1][1]<x:
                res.append([x,y]) #以数组的形式存储
            else:
                res[-1][1]=max(y,res[-1][1]) #比较b[1]和a[1]
        return res
复制代码

 

 
posted @   是冰美式诶  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示