插入区间Python解法
生活随笔
收集整理的這篇文章主要介紹了
插入区间Python解法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個 無重疊的 ,按照區間起始端點排序的區間列表。
在列表中插入一個新的區間,你需要確保列表中的區間仍然有序且不重疊(如果有必要的話,可以合并區間)。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/insert-interval
例:
輸入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
輸出:[[1,2],[3,10],[12,16]]
解釋:這是因為新的區間 [4,8] 與 [3,5],[6,7],[8,10]?重疊。
解析:
首先空判斷,然后先判斷插入頭的位置,然后判斷插入尾的位置即可。
class Solution(object):def insert(self, intervals, newInterval):""":type intervals: List[List[int]]:type newInterval: List[int]:rtype: List[List[int]]"""res = [] # 結果if not intervals: # 判空return [newInterval]i, n = 0, len(intervals) # 指針,長度while i < n and intervals[i][0] <= newInterval[0]: # 判斷頭部位置i += 1res = intervals[:i] # 前面不相干的區間直接進入結果數組if not res or res[-1][1] < newInterval[0]: # 判斷當前結果數組的尾部res.append(newInterval)else:res[-1][1] = max(res[-1][1], newInterval[1])for j in range(i, n): # 判斷尾部位置if res[-1][1] < intervals[j][0]: # 尾部小于后半段的左區間,后半段直接插入res += intervals[j:]breakelse:res[-1][1] = max(res[-1][1], intervals[j][1]) # 否則比較大小,合并并找出最大的右區間return res總結
以上是生活随笔為你收集整理的插入区间Python解法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10电脑系统没有声音如何解决
- 下一篇: html中colspan有什么用