问题
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
问题可视化
从下图可以看出来,在出现递减的情况下,如果删除4号点/5号点都没有用的话,那么这这个list就不可能non-decreasing。
问题解决
思路:创建两个数组one 和 two都等于A ,one删除“4号点”, two删除“5号点”;
- 如果删除一个元素后,能保持递增,sorted(one) = one or sorted(two) =two, 就返回True。
- 如果删除一个元素后的one 和 two还不能non-decreasing,那么就返回Flase了。
class Solution(object):
def checkPossibility(self, A):
one = A[:]
two = A[:]
for i in range(len(A)-1):
if(A[i]>A[i+1]):
del one[i]
del two[i+1]
break
return two == sorted(two) or one == sorted(one)