LeetCode刷题实战370:区间加法
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.
示例
示例:
输入: 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]
解题
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;
}
}