区间加法(LeetCode)

题目

假设你有一个长度为 n 的数组,初始情况下所有的数字均为 0 ,你将会被给出 k ​​​​​​ 个更新的操作。

其中,每个操作会被表示为一个三元组:[startIndex, endIndex, inc] ,你需要将子数组 A[startIndex ... endIndex] (包括 startIndex 和 endIndex)增加 inc

请你返回 k 次操作后的数组。

解题

python 复制代码
"""
这个问题可以使用差分数组来解决。
差分数组的思想是,通过记录差分,可以在常数时间内对一个区间的所有元素进行修改。
"""


def getModifiedArray(length, updates):
    # 初始化差分数组
    diff = [0] * (length + 1)

    # 处理每个操作
    for start, end, inc in updates:
        diff[start] += inc
        if end + 1 < length:
            diff[end + 1] -= inc

    # 根据差分数组计算最终数组
    result = [0] * length
    result[0] = diff[0]
    for i in range(1, length):
        result[i] = result[i - 1] + diff[i]

    return result


length = 5
updates = [
    [1, 3, 2],
    [2, 4, 3],
    [0, 2, -2]
]
print(getModifiedArray(length, updates))        # [-2, 0, 3, 5, 3]
相关推荐
Savior`L20 小时前
二分算法及常见用法
数据结构·c++·算法
quikai198120 小时前
python练习第三组
开发语言·python
mmz120721 小时前
前缀和问题(c++)
c++·算法·图论
ULTRA??21 小时前
初学protobuf,C++应用例子(AI辅助)
c++·python
CHANG_THE_WORLD21 小时前
Python 字符串全面解析
开发语言·python
努力学算法的蒟蒻21 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习1 天前
CSP认证 备考(python)
数据结构·python·算法·动态规划
databook1 天前
数据会说谎?三大推断方法帮你“审问”数据真相
后端·python·数据分析
是Dream呀1 天前
Python圣诞特辑:打造一棵会唱歌、会下雪的魔法圣诞树
开发语言·python·pygame