给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
我们是这样定义一个非递减数列的: 对于数组中所有的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。
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).
示例 1:
输入: nums = [4,2,3]
输出: true
解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
示例 2:
输入: nums = [4,2,1]
输出: false
解释: 你不能在只改变一个元素的情况下将其变为非递减数列。
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:
1 <= n <= 10 ^ 4
- 10 ^ 5 <= nums[i] <= 10 ^ 5
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
m = 0
for i in range(1,len(nums)):
if nums[i] < nums[i-1]:
m += 1
if i+1 < len(nums) and i-2 >= 0:
if nums[i-1] > nums[i+1] and nums[i-2] > nums[i]:
return False
if m > 1:
return False
return True
遍历nums中的所有数,m初始值为0,
- 如果后一个值比前一个值小,m则自加1,
- 当m>1时,返回False
- 当遍历完,m都没有变化的话,则数组不是递减数列,返回True
- 剩下特殊情况比如nums=[4,2,3],就不是,返回False
需要满足两个条件
i+1 < len(nums) and i-2 >= 0
nums[i-1] > nums[i+1] and nums[i-2] > nums[i]
执行用时 :44 ms, 在所有 Python3 提交中击败了96.35% 的用户内存消耗 :14.9 MB, 在所有 Python3 提交中击败了33.33%的用户
题目来自leetcode:
https://leetcode-cn.com/problems/non-decreasing-array/