【发布时间】:2021-02-16 13:51:19
【问题描述】:
我有以下问题(来自 AlgoExpert):
给你一个整数数组和一个整数。编写一个函数,将数组中该整数的所有实例移动到数组末尾并返回数组。 该函数应该执行这个 IN-PLACE 并且不需要维护其他整数的顺序。
例如:
array = [2,1,2,2,2,3,4,2] toMove = 2 Expected = [1,3,4,2,2,2,2,2] (the numbers 1,3,4 could be ordered differently)
我的代码:
def moveElementToEnd(array, toMove):
l = 0
r = len(array) - 1
while l < r:
if array[l] == toMove and array[r] == toMove:
r -= 1
elif array[l] != toMove and array[r] != toMove:
l += 1
elif array[l] == toMove and array[r] != toMove:
array[l], array[r] = array[r], array[l]
l += 1
r -= 1
return array
这会超时,但是当我如下更改 if 语句时,它可以正常工作:
def moveElementToEnd(array, toMove):
if len(array) < 1:
return array
l = 0
r = len(array) - 1
while l < r:
if array[l] == toMove and array[r] != toMove:
array[l], array[r] = array[r], array[l]
l += 1
r -= 1
elif array[l] != toMove and array[r] != toMove:
l += 1
else:
r -= 1
return array
第一个代码sn-p超时是什么原因?
【问题讨论】: