其他分享
首页 > 其他分享> > 665. Non-decreasing Array

665. Non-decreasing Array

作者:互联网

Given an array nums 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 nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

最多只能改变1个元素,问能不能让这个数组变成不递减数组。

考虑两种情况

1 2 3 5 4 6 -> 把5改成4就挺好,能保证后面的顺序

1 2 5 6 3 7 ->只能把3改成6而不是把6改成3

所以就是当第一次遇到后面的元素小于前面的时候,判断下应该是改前面的还是后面的元素,如果遇到第二次需要修改,那就返回false

class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        modify = False
        for i in range(1, len(nums), 1):
            if nums[i] < nums[i - 1]:
                if modify:
                    return False
                else:
                    if i - 2 >= 0 and nums[i - 2] >= nums[i]:
                        nums[i] = nums[i - 1]
                    else:
                        nums[i - 1] = nums[i]
                    modify = True
        return True
                
                
        

 

标签:Non,return,nums,665,modify,decreasing,改成,Array,array
来源: https://www.cnblogs.com/whatyouthink/p/13303085.html