一.题目:
给定一个初始为0长度为n的数组,以及一些操作.每个操作是一个元组,前两个元素代表数组区间,第三个元素代表在该区间上对数组的更新,返回经过这些操作后的数组.
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 ]
二.解题思路:
不知道怎么描述,直接上代码吧...
def getModifiedArray(length,updates):
nums = [0] * length
for update in updates:
nums[update[0]] += update[2]
if update[1] + 1 < length:
nums[update[1]+1] -= update[2]
for i in range(1,length):
nums[i] += nums[i-1]
return nums