Leetcode——665. Non-decreasing Array(一种问题可视化的方法)

问题

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

问题可视化

从下图可以看出来,在出现递减的情况下,如果删除4号点/5号点都没有用的话,那么这这个list就不可能non-decreasing。
在这里插入图片描述

问题解决

思路:创建两个数组one 和 two都等于A ,one删除“4号点”, two删除“5号点”;

  1. 如果删除一个元素后,能保持递增,sorted(one) = one or sorted(two) =two, 就返回True。
  2. 如果删除一个元素后的one 和 two还不能non-decreasing,那么就返回Flase了。
class Solution(object):
    def checkPossibility(self, A):
        one = A[:]
        two = A[:]
        for i in range(len(A)-1):
            if(A[i]>A[i+1]):
                del one[i]
                del two[i+1]
                break
        return two == sorted(two) or one == sorted(one)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值