题目:
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
Example
For
sequence = [1, 3, 2, 1]
, the output should bealmostIncreasingSequence(sequence) = false
;There is no one element in this array that can be removed in order to get a strictly increasing sequence.
For
sequence = [1, 3, 2]
, the output should bealmostIncreasingSequence(sequence) = true
.You can remove
3
from the array to get the strictly increasing sequence[1, 2]
. Alternately, you can remove2
to get the strictly increasing sequence[1, 3]
.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer sequence
Guaranteed constraints:
2 ≤ sequence.length ≤ 105
,-105 ≤ sequence[i] ≤ 105
.[output] boolean
Return
true
if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise returnfalse
.
[Python3] Syntax Tips
# Prints help message to the console
# Returns a string
def helloWorld(name):
print("This prints to the console when you Run Tests")
return "Hello, " + name
解答:
这道题看起来很简单,昨天做了一下午,很无奈,使用最笨的遍历方法计算,答案是对了,结果运行时超时了。晚上回到寝室,问了室友,室友C++刷的很六,说几分钟就搞定,结果他搞了几个小时一晚上都没有搞出来。今天早上就看了一下网友的答案,排名第一的Python答案看不懂,又看了排名第一的C++答案,就照着C++的写了个Python版本的,运行通过了。
def almostIncreasingSequence(sequence):
n = len(sequence)
p = -1
count = 0
for i in range(1,len(sequence)):
if sequence[i-1] >= sequence[i]:
p = i
count += 1
if count >= 2:#大于两个数需要删除
return False
if count == 0:#没有数需要删除
return True
if p==1 or p==n-1:#只有一个数需要删除,且这个数是第一个或者最后一个数
return True
if sequence[p-1] < sequence[p+1]:#只有一个数需要删除,这个数在中间,删除当前数,将前一个数和后一个数比较
return True
if sequence[p-2] < sequence[p]:#删除当前数前一个数,将前前一个数和当前数比较。
return True
return False