【Leetcode每日一题】57. 插入区间(区间标记)

Leetcode 每日一题
题目链接: 57. 插入区间
难度: 困难
解题思路: 设置标记数组,对区间进行染色标记,最后统一处理。不算难题,但中间有很多细节需要处理。具体看代码。
题解:

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        # 显然情况
        if len(intervals) == 0:
            return [newInterval]
        if len(newInterval) == 0:
            return intervals
        # intervals 和newInterval 相同
        if len(intervals) == 1 and (intervals[0][0] == intervals[0][1]) and (newInterval[0] == newInterval[1]) and (intervals[0][0] == newInterval[1]):
            return intervals
		
		# 整个区间左右端点
        len_max = max((intervals[-1][-1]), newInterval[-1]) + 1
        len_min = min((intervals[0][0]), newInterval[0])

		# 标记数组
        visit = [0] * max((len_max - len_min), len_max)

		#打标记
        for example in intervals:
            # 赋值为-1解决左右端点相同问题
            if example[0] == example[1]:
                visit[example[0]] = -1
            else:
                for i in range(example[0], example[1]):
                    visit[i] = 1
            

        # 赋值为-1解决左右端点相同问题
        if newInterval[0] == newInterval[1] and (visit[newInterval[0]] == 0 and visit[newInterval[0] - 1] == 0):
            visit[newInterval[0]] = -1
        else:
            for i in range(newInterval[0], newInterval[1]):
                visit[i] = 1
        


        # print(visit)
        begin, end = len_min, len_min
        res = []
        for i in range(len_min, len_max - 1):
            # 出现在首位
            if (visit[i] == -1 and i == len_min):
                res.append([i, i])
            # 左右端点相同
            if ((visit[i] == 0 or visit[i] == -1)and visit[i + 1] == -1):
                res.append([i + 1, i + 1])
            if (visit[i] == 0 or visit[i] == -1) and visit[i + 1] == 1:
                begin = i + 1
            if visit[i] == 1 and (visit[i + 1] == 0 or visit[i + 1] == -1):
                end = i + 1
                res.append([begin, end])
        

        return res

你可能感兴趣的:(Leetcode,区间问题,leetcode,Python)