codefights_almostIncerasingSequence

题目:

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].

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 return false.

[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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值