Code Signal_练习题_almostIncreasingSequence

时间:2024-06-15 12:33:44

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 be
      almostIncreasingSequence(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 be
      almostIncreasingSequence(sequence) = true.

      You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

我的解答: 

 想半天想不出来,通过查阅各个大佬的做法,发现用这种方法的挺多
def almostIncreasingSequence(sequence):
count = 0
for i in range(len(sequence)-1):
if i+1 < len(sequence) and sequence[i] >= sequence[i+1]:
count += 1
if i+2 < len(sequence) and sequence[i] >= sequence[i+2]:
count += 1
return count < 3

膜拜大佬:

上个代码还能看懂,这个来自捷克*的一位大佬的代码真懵了..啥题都能一行代码解决...
def almostIncreasingSequence(s):
return 3> sum((i >= j) + (i >= k) for i, j, k in zip(s, s[1:], s[2:] + [10**6]))