区间加法(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]
相关推荐
databook11 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室11 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三13 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271116 小时前
Python之语言特点
python
刘立军17 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI18 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机20 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v21 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机21 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django