【发布时间】:2017-07-26 20:51:23
【问题描述】:
时间限制是4000ms,但是输入太大,超过了执行时间限制。谁能告诉我在哪里以及如何优化我的代码。任务是:
给定一个整数序列作为数组,判断它是否是 可以通过不再删除来获得严格递增的序列 数组中的一个元素。
提前谢谢你。
PS:这个任务也可以在 CodeFights 上找到。
def almostIncreasingSequence(sequence): # The main function
for x in range(0,len(sequence)):
copyOfSequence = copySequence(sequence)
del copyOfSequence[x]
if checkSequence(copyOfSequence) == True:
return True
return False
def copySequence(sequence): # Create a sequence that is the same with input
copyOfSequence = sequence[::]
return copyOfSequence
#Check if the sequence is a strictly increasing sequence when I remove a element
def checkSequence(sequence):
for i in range(0, len(sequence) - 1):
if sequence[i] >= sequence[i + 1]: return False
return True
【问题讨论】:
-
提示:你真的需要两个嵌套循环吗?
-
复制和删除列表中间的元素是昂贵的操作。想出一个适用于原始列表的算法。
-
@Henry 我是新手,所以我的想法不是很好,我不知道其他方法可以替换函数 checkSequence 虽然两个嵌套循环会花费很多时间
-
@MarkTolonen 谢谢你的建议,我会努力的