Leetcode 665. Non-decreasing Array

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Non-decreasing Array

2. Solution

**解析:**Version 1首先对前后相邻的两个值进行比较,统计当前值nums[i]大于后值num[i+1]的次数,并保存当前值的索引index,如果一次没出现,说明当前数组为非递减数组,如果大于两次,只修改一个值的情况下不可能变为非递减数组。当只出现一次时,需要具体分析相关情况。当nums[index]位于数组第一个(0)或倒数第二(len(nums) - 2)的位置时,此时修改nums[index]即可满足非递减数组。当nums[index - 1] <= nums[index + 1]时,修改nums[index]可满足非递减数组。当nums[index] <= nums[index + 2]时,修改nums[index+1]可满足非递减数组。除此之外,无论是修改nums[index]还是nums[index+1]都不能变为非递减数组。

  • Version 1
class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        count = 0
        index = 0
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                count += 1
                index = i
        if count == 0:
            return True
        elif count > 1:
            return False
        else:
            if index == 0 or index == len(nums) - 2:
                return True
            elif nums[index - 1] <= nums[index + 1]:
                return True
            elif nums[index] <= nums[index + 2]:
                return True
            else:
                return False
  • Version 2
class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        count = 0
        index = 0
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                count += 1
                if count > 1:
                    return False
                index = i

        if count == 0 or index == 0 or index == len(nums) - 2 or nums[index - 1] <= nums[index + 1] or nums[index] <= nums[index + 2]:
            return True
        else:
            return False

Reference

  1. https://leetcode.com/problems/non-decreasing-array/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值