665.非递减数列(Easy)
题解
https://leetcode-cn.com/problems/non-decreasing-array/solution/tan-xin-si-xiang-by-zhang-mo-san/
代码示例
Python 示例
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
errors = 0
for idx in range(len(nums) - 1):
if nums[idx] > nums[idx + 1]:
# 只有当修改不会破坏前一个元素的单调性才允许
# 不能出现 3 4 2 => 3 2 2 的情况
if (idx == 0 or nums[idx - 1] <= nums[idx + 1]):
nums[idx] = nums[idx + 1] # 此处修改会影响 nums[i] 与 nums[i - 1] 的递减关系
else: # 保底方案
nums[idx + 1] = nums[idx]
errors += 1
return bool(errors <= 1)
Go 示例
func checkPossibility(nums []int) bool {
errors := 0
n := len(nums)
for i:= 0; i < n - 1; i++ {
if errors > 1 { return false }
if nums[i] > nums[i + 1] {
if i == 0 || nums[i - 1] <= nums[i + 1] {
nums[i] = nums[i + 1]
} else {
nums[i + 1] = nums[i]
}
errors++
}
}
return errors <= 1
}