665. Non-decreasing Array -- Python

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

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].

思路:
琢磨了半天才有了一个勉强可行的思路,就是复制2个数组(a,b)出来,只要碰到 nums[i]>nums[i+1] 的情况,前一个(a)直接删除 nums[i] 再比较删除后的数组是否是已经排序好的(a 是不是等于 sorted(a) ),后一个数组(c)直接删除 nums[i+1] 再比较删除后的数组是否是已经排序好的(c 是不是等于 sorted(c) ),只要二者之间有一个是已经排序好的就返回 True 否则 返回 False。

(刚开始就是想单纯比较 nums[i]>nums[i+1] 时,如果nums[i+1] 是不是数组中最小的数,如果是则就删除num[i+1],观察删除该元素后是否是非递减数组,如果nums[i+1]不是最小的,就删除nums[i],再观察删除该元素后是否是非递减数组。沿着上面的思路,碰到一些特定的情况没法通过,例如 [1,3,4,2,5] ,或者[1,2,4,5,3],然后就越改越细,越改越复杂。).

我的代码:

class Solution:
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        import copy
        a = copy.deepcopy(nums)
        b = copy.deepcopy(nums)

        if len(nums)>2:
            for i in range(1,len(nums)-1):
                if a[i]>a[i+1]:
                    del a[i]
                    del b[i+1]
                    if (a == sorted(a)) or (b==sorted(b)):
                        return True
                    else:
                        return False

            else:
                return True
        else:
            return True

然后对程序稍加修改,速度快了接近4倍:

class Solution:
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        a,b=nums[:],nums[:]
        if len(nums)>2:
            for i in range(1,len(nums)-1):
                if a[i]>a[i+1]:
                    del a[i]
                    del b[i+1]
                    return ((a == sorted(a)) or (b==sorted(b)))

            else:
                return True
        else:
            return True

参考代码:
思路和我的是一样的,只是他是直接替换,我是删除,然后再比较。

class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        one, two = nums[:], nums[:]
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                one[i] = nums[i + 1]
                two[i + 1] = nums[i]
                break
        return one == sorted(one) or two == sorted(two)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值