区间加法(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]
相关推荐
YsyaaabB2 小时前
Python 数值分析
python
阿洛学长2 小时前
计算机二级 Python 基本操作题(15 分)真题笔记(0101 ~ 1903 全套)
python·pycharm
醇氧3 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
weixin199701080163 小时前
[特殊字符]️《二手ERP对接电商平台的总体方案:统一数据模型 + 事件驱动 + 灰度上线6原则》(附Python源码)
大数据·python
大熊背3 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝3 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
滚雪球~3 小时前
量化交易 防止Windows电脑自动更新并重启
python·量化
参.商.3 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
HZZD_HZZD3 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
L@ncor4 小时前
第二章可能出现的问题
人工智能·python