LeetCode 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]
思路

区间的操作,一般可以采用前缀和(这个在此时间复杂度过高会超时),前缀和的差分和线段树

前缀和的差分

前缀和序列S0,S1…Sn的差分序列就等于原序列a0,a1…an,其中Sn-Sn-1 = an。
原序列a0,a1…an的差分序列为b0,b1…bn,其中an-an-1 = bn,则对差分序列求前缀和就可以得到原序列。
差分序列的好处是如果要对原序列的一个区间[l,r]的所有值加val,原序列上要操作r-l+1次,在差分序列上只需要操作两次(b[l] + val,b[r+1] - val),

具体过程如下

  • 构建一个二维数组,即[0,0,0,0…]
  • 根据区间操作方法求其差分数组
  • 求差分数组的前缀和

时间复杂度分析:O(n)

c++代码
class Solution {
    
    
public:
    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
    
    
        vector<int> ans(length, 0);
        for (int i = 0; i < updates.size(); i++) {
    
    
            ans[updates[i][0]] += updates[i][2];
            if (updates[i][1] + 1 < length) {
    
       
                ans[updates[i][1] + 1] -= updates[i][2];    // 卷回去
            }
        }
        for (int i = 1; i < length; i++) {
    
    
            ans[i] += ans[i - 1];
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_48322523/article/details/120829303