区间加法(LeetCode)

题目

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

其中,每个操作会被表示为一个三元组:startIndex, endIndex, inc ,你需要将子数组 AstartIndex ... 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]
相关推荐
言乐61 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
Kx_Triumphs1 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
YUS云生2 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
旖-旎2 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
智写-AI2 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
yuhuofei20212 小时前
【Python入门】了解掌握Python中函数的基本使用
python
轻颂呀3 小时前
约瑟夫环问题
算法
白帽小阳4 小时前
2026前端面试题!(附答案及解析)
javascript·网络·python·安全·web安全·网络安全·护网行动