topic
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.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example:
[13, 4, 7] should return true, since we can modify 13 to any value 4 or less, to make it non-decreasing.
[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?
analysis
First, it is clear that there is at most only a pair of numbers decreasing. Because if more than one pair, then the adjustment in any case can not be successful.
It is assumed that the number 2 is B, C.
now only need to iterate over each location. For each position of the number of adjacent B, C is determined. If B> C:
same time it needs to consider the number before and after taking i.e. A and D. A, B, C, D four consecutive numbers. The following logic:
If B <= D, may be adjusted by increasing the success C A, B, C, D of the order of diminished;
if A <= C, then A can be successfully adjusted by reducing the B, B , C, D is diminished order;
Another consideration end to end across the special case, if this time is not only the number of four consecutive number 3, the adjustment mode will be more free.
Other cases, certainly not successful adjustment, direct returns false.
Otherwise, continue to traverse the other position, comprehensive judgment.
Time complexity is O (1).
Code
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