665. Non-decreasing Array Python代码

  1. 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).

Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can’t get a non-decreasing array by modify at most one element.
Note: The n belongs to [1, 10,000].

#author ncepu_David
class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        """
        当发生递减时:比如4 2 3 我们发现4>2,一般我们为了实现非递减,可以把4变成2(变小),也可以2变成4(变大),两种方式尽量选第一种(变小),因为第二种方法可能导致后面的情况又出现递减。
        再考虑其他情况,比如 -1 4 2 3 和 3 4 2 3 我们发现第一个数组中4可以变成2但是第二个数组中4不能变成2,只能考虑将2变成4(当然第二个数组不满足非递减,2变成4后:4 3又递减了)。问题的关键在于4左右两个数的大小关系。
		综上:我们只要用一个flag记录发生递减时交换的次数,只能交换一次,当第二次发生递减时就不用做交换了,直接根据判断False
        """
        flag=False 			#修改标志位,最多只可以改一次
        for i in range(len(nums)-1):
            if nums[i]>nums[i+1]:		#问题的关键就是找到递减位
                if(flag):				#最多只可以改一次,初值是False,改过一次就是True,因此实现最多改一次
                    return False
                else:
                    if(i==0 or nums[i+1]>nums[i-1]): #当递减位是第一个值或者递减位右边的值大于左边的,则将递减位变小
                        nums[i]=nums[i+1]
                    else:    #反之,递减位右边的值小于左边的,则将递减位右边的值变大。
                        nums[i+1]=nums[i]
                    flag=True
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值