[Leetcode] 370. Range Addition 解题报告

本文介绍了一种高效解决数组批量更新问题的方法。面对大量的更新操作,直接更新每个元素将导致效率低下。文章提出一种巧妙的解决方案,只需更新区间的起始和结束位置附近的元素,大大提升了算法效率。

题目

Assume you have an array of length n initialized with all 0's and are given k update operations.

Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc.

Return the modified array after all k operations were executed.

Example:

Given:

    length = 5,
    updates = [
        [1,  3,  2],
        [2,  4,  3],
        [0,  2, -2]
    ]

Output:

    [-2, 0, 3, 5, 3]

Explanation:

Initial state:
[ 0, 0, 0, 0, 0 ]

After applying operation [1, 3, 2]:
[ 0, 2, 2, 2, 0 ]

After applying operation [2, 4, 3]:
[ 0, 2, 5, 5, 3 ]

After applying operation [0, 2, -2]:
[-2, 0, 3, 5, 3 ]

思路

这道题目的直观解法很容易想到,就是每次更新区间内的所有元素。但是这种算法肯定是无法通过面试的。其实我们每次没必要把区间内的每个值都更新,只需要更新起点和终点后的一点即可。这样做的好处是:因为我们把增加的值放在了起点,而终点后一点相应减去了增加的值,所以再扫描的时候,把之前累加的和作为最终值即可。是不是很巧妙?

算法的时间复杂度是O(k) + O(n),其中k是更新的次数,n是数组的长度。空间复杂度是O(1)。

代码

class Solution {
public:
    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
        vector<int> sums(length, 0);
        for(auto val : updates) {
            sums[val[0]] += val[2];
            if(val[1] < length - 1) {
                sums[val[1] + 1] -= val[2];
            }
        }
        int sum = 0;
        for(int i = 0; i < length; ++i) {
            sum += sums[i];
            sums[i] = sum;
        }
        return sums;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值