Range Addition解题报告

2017-09-06  本文已影响42人  黑山老水

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,然后再最后统一进行操作2,即可得到所求的数组。

Tips:

O(length + updates.size())

Time Complexity:

完整代码:

vector<int> getModifiedArray(int length, vector<vector<int>>& updates) 
    {
        vector<int> 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;
    }
上一篇 下一篇

猜你喜欢

热点阅读