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 first4to1to 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.length1 <= 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

本文探讨如何判断给定数组是否可以通过调整最多一项元素,使其成为非递减序列。提供了两种解决方案:一是限制相邻元素的升降操作,二是允许首元素自由降低,其余仅降升结合。
418

被折叠的 条评论
为什么被折叠?



