区间加法(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]
相关推荐
每天吃饭的羊1 小时前
Chrome DevTools MCP
python
wabs6662 小时前
关于图论【最短路径之Bellman_ford 算法(单源有限最短路)|卡码网96.城市间货物运输III的思考】
数据结构·算法·图论·卡码网·bellman_ford·单源有限最短路
水獭比特3 小时前
localhost 不是安全边界:给 Agent Web 入口补上四层门禁
人工智能·python
Generalzy3 小时前
Whisper + VAD + TTS:一套完整的 Python 本地语音处理流水线
python·whisper·语音识别
qpsj3 小时前
让 LLM 控制 AutoCAD/ZWCAD:COM 自动化 + MCP 封装
python·llm
赟爸3 小时前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python
lsylalalala4 小时前
常见的排序算法1
数据结构·算法·排序算法
怪奇云呼军4 小时前
从声音特征到 CRM 回流:闪电智能 Voice Agent 沟通策略自适应系统 v1 实战
android·人工智能·python·音视频·语音识别
jufeng13074 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 6 篇】
python·ai agent·记忆系统
想吃火锅10054 小时前
【leetcode】54. 螺旋矩阵
算法·leetcode·矩阵