Given an array nums
with n
integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1]
holds for every i
(0-based) such that (0 <= i <= n - 2
).
Example 1:
Input: nums = [4,2,3] Output: true Explanation: You could modify the first4
to1
to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1] Output: false Explanation: You can't get a non-decreasing array by modify at most one element.
Constraints:
n == nums.length
1 <= n <= 104
-105 <= nums[i] <= 105
---------------------------
两种方案:
方案一:降低i-1不行 AND 升高i也不行
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
drop_times,l = 0,len(nums)
for i in range(1,l):
if (nums[i] < nums[i-1]):
drop_times += 1
if (drop_times >= 2):
return False
if ((i >= 2 and nums[i-2] > nums[i]) and (i+1 < l and nums[i-1] > nums[i+1])): #降低i-1不行 AND 升高i也不行
return False
return True
方案二:除了首元素可以无限降,其他情况的下跌nums[i-1]>nums[i],尝试把i填高,剩下的给下轮循环解决
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
drop_times,l = 0,len(nums)
for i in range(1,l):
if (nums[i] < nums[i-1]):
drop_times += 1
if (drop_times >= 2):
return False
if (i>=2 and nums[i-2]>nums[i]):
nums[i] = nums[i-1]
return True