首页 > 其他 > 详细

665. Non-decreasing Array

时间:2020-07-15 01:08:16      阅读:43      评论:0      收藏:0      [点我收藏+]

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
                
                
        

 

665. Non-decreasing Array

原文:https://www.cnblogs.com/whatyouthink/p/13303085.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!