假设你有一个长度为 n 的数组,初始情况下所有的数字均为 0,你将会被给出 k 个更新的操作。
其中,每个操作会被表示为一个三元组:[startIndex, endIndex, inc],你需要将子数组 A[startIndex ... endIndex](包括 startIndex 和 endIndex)增加 inc。
请你返回 k 次操作后的数组。
示例:
输入: 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]
提示 1
Thinking of using advanced data structures? You are thinking it too complicated.
提示 2
For each update operation, do you really need to update all elements between i and j?
提示 3
Update only the first and end element is sufficient.
提示 4
The optimal time complexity is O(k + n) and uses O(1) extra space.
解法1:差分数组
Java版:
class Solution {
public int[] getModifiedArray(int length, int[][] updates) {
int[] diff = new int[length];
for (int[] update: updates) {
diff[update[0]] += update[2];
if (update[1] + 1< length) {
diff[update[1] + 1] -= update[2];
}
}
for (int i = 1; i < length; i++) {
diff[i] += diff[i - 1];
}
return diff;
}
}
Python3版:
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
diff = [0] * length
for start, end, inc in updates:
diff[start] += inc
if end + 1 < length:
diff[end + 1] -= inc
for i in range(1, length):
diff[i] += diff[i - 1]
return diff
复杂度分析
- 时间复杂度:O(k+n) ,每个操作值修改两个元素,即修改操作是 O(1) 的,最后遍历差分数组是 O(n) 的。
- 空间复杂度:O(n) 。