Algorithm 如何提高计算最小移动次数的算法性能速度?
我参与代码战,并让任务找到从输入中获得严格递增序列所需的最少移动次数。作为输入,有整数数组,根据规则,我可以在数组中每移动一次就增加一个元素Algorithm 如何提高计算最小移动次数的算法性能速度?,algorithm,performance,python-3.x,loops,cycle,Algorithm,Performance,Python 3.x,Loops,Cycle,我参与代码战,并让任务找到从输入中获得严格递增序列所需的最少移动次数。作为输入,有整数数组,根据规则,我可以在数组中每移动一次就增加一个元素 inputArray: [1, 1, 1] Expected Output:3 inputArray: [-1000, 0, -2, 0] Expected Output:5 inputArray: [2, 1, 10, 1] Expected Output:12 inputArray: [2, 3, 3, 5, 5, 5, 4, 12, 12, 1
inputArray: [1, 1, 1]
Expected Output:3
inputArray: [-1000, 0, -2, 0]
Expected Output:5
inputArray: [2, 1, 10, 1]
Expected Output:12
inputArray: [2, 3, 3, 5, 5, 5, 4, 12, 12, 10, 15]
Expected Output:13
还有输入和输出的条件:
[time limit] 4000ms (py3)
[input] array.integer inputArray
3 ≤ inputArray.length ≤ 105,
-105 ≤ inputArray[i] ≤ 105
[output] integer
我提出了以下解决方案:
def arrayChange(inputArray):
k=0
for i in range(len(inputArray)-1):
if (inputArray[i]<inputArray[i+1]) == False:
while inputArray[i+1]<=inputArray[i]:
inputArray[i+1] = inputArray[i+1] + 1
k +=1
return k
def阵列更改(输入阵列):
k=0
对于范围内的i(len(inputArray)-1):
如果(inputArray[i]现在一次增加1。当前有以下代码段:
输入阵列[i+1]=输入阵列[i+1]+1
与其每次增加1,为什么不一次添加所有数字呢?例如,如果您有列表[1,3,0]
,在最后一个元素中添加4是有意义的。这样做比添加1 4次要快得多。@fileyfood500给了我一个非常有用的提示,下面是我的解决方案:
deltX=0
for i in range(len(a)-1):
if (a[i]<a[i+1]) == False:
deltX1 = abs(a[i+1]-a[i])+1
a[i+1] = a[i+1] + deltX1
deltX += deltX1
print(deltX)
deltX=0
对于范围内的i(len(a)-1):
如果(a[i]def阵列更改(输入阵列):
计数=0
对于范围(1,len(输入阵列))中的i:
当输入时[i]
def arrayChange(inputArray):
count = 0
for i in range(1,len(inputArray)):
while inputArray[i] <= inputArray[i-1]:
c = inputArray[i]
inputArray[i]= inputArray[i-1]+1
count += inputArray[i] - c
return count