码迷,mamicode.com
首页 > 其他好文 > 详细

665. Non-decreasing Array

时间:2020-07-15 01:12:51      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:and   you   pre   array   fine   改变   ase   false   pos   

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

标签:and   you   pre   array   fine   改变   ase   false   pos   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!