区间加法(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]
相关推荐
紫金修道2 小时前
【DeepAgent】概述
开发语言·数据库·python
书到用时方恨少!2 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
Warson_L3 小时前
Python 常用内置标准库
python
Warson_L3 小时前
Python 函数的艺术 (Functions)
python
Warson_L3 小时前
Python 流程控制与逻辑
后端·python
long_songs3 小时前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘
袋鼠云数栈3 小时前
集团数字化统战实战:统一数据门户与全业态监管体系构建
大数据·数据结构·人工智能·多模态
必然秃头3 小时前
Python 环境安装及项目构建指南
python
Warson_L3 小时前
Python 四大组合数据类型 (Collection Types)
后端·python
廋到被风吹走3 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python