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).
Example 1:
Input: [4,2,3] Output: True Explanation: You could modify the first4
to1
to get a non-decreasing array.
Example 2:
Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element.
Note: The n
belongs to [1, 10,000].
解:
Find index k so that nums[k] > nums[k + 1]
- Not found: true
- Found more than one: false
- Found one:
- If at 0 or n - 2, can easily change first or last num, true
- Otherwise check if removing nums[k] or nums[k+1] make it non-decreasing. If can, then change nums[k] or nums[k+1] can make nums non-decreasing.
class Solution: def checkPossibility(self, nums: List[int]) -> bool: size=len(nums) if size<=2: return True; k=-1 #0-n-1 2 3 3 2 4 4 2 3 // 2 3 3 2 4 移除第k+1个//-1 4 2 3移除第k个 for i in range(size-1): if nums[i]>nums[i+1]: if k>=0: return False k=i if k==-1 or k==0 or k==size-2: return True #移除第k个数看剩下的是否还是非递减 else: return nums[k]<=nums[k+2] or nums[k-1]<=nums[k+1]