LeetCode 370. 区间加法

370. 区间加法

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

其中,每个操作会被表示为一个三元组:[startIndex, endIndex, inc],你需要将子数组 A[startIndex ... endIndex](包括 startIndex 和 endIndex)增加 inc

请你返回 k 次操作后的数组。

示例:

输入: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
输出: [-2,0,3,5,3]

解释:

初始状态:
[0,0,0,0,0]

进行了操作 [1,3,2] 后的状态:
[0,2,2,2,0]

进行了操作 [2,4,3] 后的状态:
[0,2,5,5,3]

进行了操作 [0,2,-2] 后的状态:
[-2,0,3,5,3]

提示 1

Thinking of using advanced data structures? You are thinking it too complicated.


提示 2

For each update operation, do you really need to update all elements between i and j?


提示 3

Update only the first and end element is sufficient.


提示 4

The optimal time complexity is O(k + n) and uses O(1) extra space.

解法1:差分数组

Java版:

class Solution {
    public int[] getModifiedArray(int length, int[][] updates) {
        int[] diff = new int[length];
        for (int[] update: updates) {
            diff[update[0]] += update[2];
            if (update[1] + 1< length) {
                diff[update[1] + 1] -= update[2]; 
            }
        }
        
        for (int i = 1; i < length; i++) {
            diff[i] += diff[i - 1];
        }
        return diff;
    }
}

Python3版:

class Solution:
    def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
        diff = [0] * length
        for start, end, inc in updates:
            diff[start] += inc 
            if end + 1 < length:
                diff[end + 1] -= inc 
        
        for i in range(1, length):
            diff[i] += diff[i - 1]
        return diff

复杂度分析

  • 时间复杂度:O(k+n) ,每个操作值修改两个元素,即修改操作是 O(1) 的,最后遍历差分数组是 O(n) 的。
  • 空间复杂度:O(n) 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值