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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)