Range Addition解题报告

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:

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 ]

Link:

https://leetcode.com/problems/range-addition/description/

解题方法:

除了直接按照题意暴力破解,还有一种使用加法结合律的方法,以以上例子为例:
当有只有一个命令:[1, 3, 2]

  • 操作1
    start位置进行+= 2的操作,在end+1的位置进行-=2的操作。
  • 操作2
    当我们遍历整个数组进行a[i] += a[i - 1]的操作时,即可得到我们想要的数组。

这道题所有的操作都是加法,所以不管有多少个命令,我们都先进行操作1,然后再最后统一进行操作2,即可得到所求的数组。

Tips:

O(length + updates.size())

Time Complexity:

完整代码:

vector getModifiedArray(int length, vector>& updates) 
    {
        vector result(length);
        for(auto a: updates)
        {
            result[a[0]] += a[2];
            if(a[1] + 1 < length)
                result[a[1] + 1] -= a[2];
        }
        for(int i = 1; i < length; i++)
            result[i] += result[i - 1];
        return result;
    }

你可能感兴趣的:(Range Addition解题报告)