LeetCode 665. Non-decreasing Array

231 篇文章 0 订阅
120 篇文章 1 订阅

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 first 4 to 1 to 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.length
  • 1 <= 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值