LeetCode 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:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
  • 给定一个数组,他本应是前后递增(或相等)的,可是现在他身上可能有一个(或多个)地方长瘤了,现在只给你一刀的机会,你能不能救救这个倒霉孩子?
class Solution:
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        l = len(nums)
        counter = 0
        for i in range(1, l):
            if nums[i] < nums[i-1]:
                counter += 1
                if i+1 < l and i-2 >= 0: 
                    f = nums[i+1] < nums[i-1]
                    s = nums[i-2] > nums[i]  
                    if s and f:
                        return False
            if counter > 1:
                return False  
        return True

  • range()是个聪明的孩子,最擅长的就是掰手指(或许也有脚趾)来数数:
    • range(start, stop[, step])
    • start–从哪开始数
    • stop–数到哪里
    • step–一次掰几个手指
>>>range(10)        # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)  # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
  • 现在我们先来病情诊断:
    • 假设正常的肚皮是:[5,6]
    • 如果出现了:[9,6]
      • 警报,发现肿瘤!
      • 快,在周围检查检查
      • [8,9,6,7]
      • “扩散了,这倒霉孩子没救了,拿去煲汤吧。”
      • [5,9,6,7]或者[8,9,6,10]
      • “行吧,不过再来一次这种情况这孩子就死定了。”

猜你喜欢

转载自blog.csdn.net/weixin_41084236/article/details/81136422