1、题目描述
2、解题思路
创建一个 int[] 数组 ans,长度为 length。
对于每一个给定的 [startIndex, endIndex, inc] 我们可以理解成如下:
把 ans 的 [startIndex,length-1] 都加上了 inc,然后再把 [endIndex+1, length-1] 再减去 inc。
具体的操作是:
1、先 ans[startIndex] += val,ans[endIndex+1] += -val;
3、然后 [startIndex,length-1] 遍历进行 ans[i] += ans[i-1]。
这样做的目的是因为所有的三元组 [startIndex, endIndex, inc] 对数组 ans 的操作是独立的,我们先对所有的三元组对 ans 的操作在边界上做好,然后遍历一遍 ans 数组即可同时执行完所有三元组对 ans 的操作。
3、解题代码
class Solution {
public int[] getModifiedArray(int length, int[][] updates) {
int[] ans = new int[length];
int start, end, val;
for (int[] update : updates) {
start = update[0];
end = update[1];
val = update[2];
ans[start] += val;
if (end < length - 1) {
ans[end + 1] -= val;
}
}
for (int i = 1; i < length; i++) {
ans[i] += ans[i - 1];
}
return ans;
}
}