LintCode 903 · Range Addition (差分数组经典题)

文章讨论了解决数组更新操作的问题,介绍使用差分数组的方法,以及前缀和数组、线段树和树状数组在处理区间增减数操作中的区别和适用场景。

LintCode 903 · Range Addition
Algorithms
Medium
Description
Description
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]
]
return [-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 ]

解法1:差分数组

class Solution {
public:
    /**
     * @param length: the length of the array
     * @param updates: update operations
     * @return: the modified array after all k operations were executed
     */
    vector<int> getModifiedArray(int length, vector<vector<int>> &updates) {
        int n = updates.size();
        if (n == 0) return {};
        vector<int> diffs(length, 0);
        vector<int> res(length, 0);
        for (int i = 0; i < n; i++) {
            diffs[updates[i][0]] += updates[i][2];
            if (updates[i][1] + 1 < length) {  //注意这个细节!
                diffs[updates[i][1] + 1] -= updates[i][2];
            }
        }
        res[0] = diffs[0];
        for (int i = 1; i < length; i++) {
            res[i] = res[i - 1] + diffs[i];
        }
        return res;
    }
};

注意:什么时候用前缀和数组?什么时候用差分数组?什么时候又用线段树和树状数组?
根据链接:https://blog.youkuaiyun.com/weixin_55516868/article/details/128717574
前缀和数组、差分数组、线段树、树状数组均用于处理区间问题,但有不同应用场景
前缀和数组:用于处理 连续多次取区间和 操作的情况,取区间和期间不能对原数组进行区间增减数操作
差分数组:用于处理 多次区间增减数操作,最后读取一次区间和(即修改期间读取不频繁) 操作的情况
线段树:用于处理 多次区间增减数操作,期间多次读取区间和(即修改期间读取频繁) 操作的情况
树状数组:用于处理 多次区间增减数操作,期间多次读取区间和(即修改期间读取频繁) 操作的情况,同线段树的情况、但树状数组更加简单且不支持区间更新,线段树支持区间更新但编码复杂

解法2:线段树应该也可以做

解法3:树状数组应该也可以做

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值