665.Non-decreasingArray(非递增数列)(python3)
原创给你一个长度 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 cant 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/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123


