题目:
自己用最常规的思路写了下:
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
target = []
for i in range(length):
target.append(0)
if not updates:
return target
length1 = len(updates)
for j in range(length1):
start = updates[j][0]
end = updates[j][1]
opreate = updates[j][2]
for i in range(start,end+1):
target[i] += int(opreate)
return target
提交,最后一个很长的用例没办法跑过:
ps:
自己在本地写的带输入的:
while True:
n = int(input())
target = []
op = []
strs = list(map(int,input().split()))
while strs:
op.append(strs[0:3])
strs = strs[3::]
for i in range(n):
target.append(0)
length = len(op) #记录操作的次数
for j in range(length):
start = op[j][0]
end = op[j][1]
opreate = op[j][2]
for i in range(start,end+1):
target[i] += int(opreate)
print(target)
看了题解,此题可以用差分数组的方法做:
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
target = [0] * (length+1)
length1 = len(updates)
for j in range(length1):
start = int(updates[j][0])
end = int(updates[j][1])
opreate = int(updates[j][2])
target[start] += opreate
target[end+1] -= opreate
for i in range(1,length):
target[i] += target[i-1]
return target[0:length]