You are given an array of integers in an arbitrary order. Return whether or not it is possible to make the array non-decreasing by modifying at most 1 element to any value.less
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).code
Example:element
[13, 4, 7] should return true, since we can modify 13 to any value 4 or less, to make it non-decreasing.it
[13, 4, 1] however, should return false, since there is no way to modify just one element to make the array non-decreasing.
Can you find a solution in O(n) time?io
首先,很明显最多只能存在一对递减的数字。由于若是多于一对,则不管如何调整都不可能成功。
假设这2个数为 B, C.
如今只须要遍历一遍每一个位置。对于每一个位置的相邻数对 B, C 进行判断。若是 B > C:
那么同时须要考虑其先后2个数 A 和 D. 即取 A, B, C, D 这4个连续的数。有以下逻辑:
若 B <= D, 则能够经过增大 C 来成功调整 A, B, C, D 为不减的次序;
若 A <= C,则能够经过减少 B 来成功调整 A, B, C, D 为不减的次序;
另外须要考虑首尾两端的特殊状况,此时若是没有连续的4个数而只有3个数,则调整方式也会更自由。
其余状况,则确定没法调整成功,直接返回 false.
不然,继续遍历其余位置,综合判断。class
时间复杂度为 O(1).遍历
def check(lst): found_dec = False for i in range(0, len(lst) - 1): if lst[i] > lst[i+1]: if found_dec: return False # 出现了多于一对递减的数字对 found_dec = True if i > 0 and lst[i-1] <= lst[i+1]: continue if i == 0 or i == len(lst) - 2: continue if i < len(lst) - 2 and lst[i] <= lst[i+2]: continue return False else: continue return True print check([13, 4, 7]) # True print check([5,1,3,2,5]) # False