LeetCode 370. Range Addition

Assume you have an array of length n initialized with all 0's and are given kupdate 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:

Input: 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]

此题的最优解时间复杂度为O(k + n),空间复杂度为O(1)

对于每一个triplet,将其三个元素分别称为 start,end,inc。每个triplet要将start到end范围内到所有元素增加inc。

创建一个长度为length的数组后,分为两个步骤来解决这个问题,第一个阶段是将所有triplet读入,在start处增加inc,在end+1处减去inc。

第二个阶段是开始累加,从左开始,将累加的和更新称为当前的值。

public int[] getModifiedArray(int length, int[][] updates) {
        int[] res = new int[length];
        for(int[] triplet : updates) {
            int start = triplet[0];
            int end = triplet[1];
            int add = triplet[2];
            res[start] += add;
            if(end < length - 1) res[end + 1] -= add;
        }
        for(int i = 1; i < length; i++) {
            res[i] += res[i - 1];
        }
        return res;
    }

这个思路在之前做my calendar II题目的时候也用过,当时是用treemap<Integer,Integer>来存,key是时间,value是事件数目,在事件的开始事件value+1, 结束时间value-1.

猜你喜欢

转载自www.cnblogs.com/rookielet/p/10721730.html