区间加法(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]
相关推荐
玉树临风ives4 分钟前
atcoder ABC 452 题解
数据结构·算法
chushiyunen26 分钟前
python rest请求、requests
开发语言·python
cTz6FE7gA27 分钟前
Python异步编程:从协程到Asyncio的底层揭秘
python
feifeigo12328 分钟前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
baidu_huihui34 分钟前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳36 分钟前
Python从入门到精通day63
开发语言·python
lbb 小魔仙36 分钟前
Python_RAG知识库问答系统实战指南
开发语言·python
fengfuyao9851 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
FreakStudio1 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
python·单片机·嵌入式·电子diy