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