区间加法(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]
相关推荐
yunhuibin11 小时前
LeNet
人工智能·python
一个不知名程序员www17 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
jaray18 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
Psycho_MrZhang18 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Sarvartha18 小时前
C++ STL 栈的便捷使用
c++·算法
web3.088899918 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python
少云清18 小时前
【性能测试】15_JMeter _JMeter插件安装使用
开发语言·python·jmeter
夏鹏今天学习了吗19 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
光羽隹衡19 小时前
机器学习——TF-IDF实战(红楼梦数据处理)
python·tf-idf
飞Link19 小时前
深度解析 MSER 最大稳定极值区域算法
人工智能·opencv·算法·计算机视觉