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.csdn.net/weixin_55516868/article/details/128717574
前缀和数组、差分数组、线段树、树状数组均用于处理区间问题,但有不同应用场景
前缀和数组:用于处理 连续多次取区间和 操作的情况,取区间和期间不能对原数组进行区间增减数操作
差分数组:用于处理 多次区间增减数操作,最后读取一次区间和(即修改期间读取不频繁) 操作的情况
线段树:用于处理 多次区间增减数操作,期间多次读取区间和(即修改期间读取频繁) 操作的情况
树状数组:用于处理 多次区间增减数操作,期间多次读取区间和(即修改期间读取频繁) 操作的情况,同线段树的情况、但树状数组更加简单且不支持区间更新,线段树支持区间更新但编码复杂

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

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

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/132683957
今日推荐