注意:如果数组是[1,1,1,2,3],它也是False,因为它有重复。
我的程序完全正常工作,但是在测试数组上有5,000个条目,它不适合4秒窗口完成。
我的代码:
def almostIncreasingSequence(s):
l = len(s);
R1 = [] #RESULT AFTER 1st test
R2 = [] #RESULT AFTER 2nd test
T2 = [] #All true, to remove false positives
#TEST ONE 1 BY 1
for n in range(0,l):
one = s[:];
one.pop(n)
k = one[:];
if sorted(k)==k:
R1.append("T")
T2.append(k)
#else:
R1.append("F")
#TEST 2, REMOVE FALSE POSITIVE DUPLICATES
if "T" in R1:
# print("will go throught",T2)
secondTEST = len(T2)
for n in range(0,secondTEST):
#print("Running False Positive test for array # ",n)
duplicates = []
duplicates = T2[n]
if (len(duplicates) != len(set(duplicates))):
# print("DUPLICATE FOUND IN",T2[n])
#if found add F to R2
R2.append("F")
else:
# print("no duplicate found in, so TRUE ",T2[n])
R2.append("T")
#tf.append("F")
if "T" in R2:
return True
else:
return False
我做的是: 第一个循环删除了1个元素,检查它是否适用于所有情况。如果为True则保存数组以对其运行第二次测试。当循环结束时,如果存在传递为True的数组,则第二次测试通过检查是否有任何重复数字来消除误报。如果他们做了假阳性,如果没有它的真实。
最后我在第二次测试后获得数组,例如[T,F,F],如果它包含T,那么其中一个数组不是误报。
我的问题是如何改善我的方法的表现?我尝试不将“F”写入数组,如果为false,但它仍然不会提高性能,在不到4秒的时间内传递5.000数组。
答案 0 :(得分:3)
提高性能的最有效方法是使用更好的算法。尝试这样的事情[这是伪代码,你必须自己编写实际的Python]
# If a sequence is not strictly increasing then there will be a point at
# which a[n] >= a[n+1]. We'll call that a reversal.
Scan the array for a reversal
If you find a reversal,
# At this point you have an option of removing element n,
# or removing element n+1. Try them one at a time:
if a[n-1] < a[n+1] then check the results of removing element n
call another method that checks for strict ordering for the rest
of the array. [i.e. n+1 .. array.size]
If that method returns true, then return true
else fall thru to next check
# if you get here, removing element n won't work:
if a[n] < a[n+2] then check the results of removing element n+1
call the method that checks for strict ordering for the rest
of the array. [i.e. n+2 .. array.size]
return whatever value it returns
else removing element n+1 won't work either
return false
# if you get here, you didn't find any reversals.
return true
请注意,无需实际删除该元素,因为问题只是确定您是否可以删除它。将输入视为不可变为既可以提高性能,又可以通过删除试验来消除引入错误的可能性。&#34;
您必须非常小心地编码,以避免数组末端的边界条件。