• 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 1element.

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

    解:

    Find index k so that nums[k] > nums[k + 1]

    • Not found: true
    • Found more than one: false
    • Found one:
      • If at 0 or n - 2, can easily change first or last num, true
      • Otherwise check if removing nums[k] or nums[k+1] make it non-decreasing. If can, then change nums[k] or nums[k+1] can make nums non-decreasing.
        class Solution:
            def checkPossibility(self, nums: List[int]) -> bool:
                size=len(nums)
                if size<=2:
                    return True;
                k=-1
                #0-n-1  2 3 3 2 4    4 2 3  // 2 3 3 2 4 移除第k+1个//-1 4 2 3移除第k个
                for i in range(size-1):
                    if nums[i]>nums[i+1]:
                        if k>=0:
                            return False
                        k=i
                if k==-1 or k==0 or k==size-2:
                    return True
                #移除第k个数看剩下的是否还是非递减
                else:
                    return nums[k]<=nums[k+2] or nums[k-1]<=nums[k+1]
                    
  • 相关阅读:
    echarts
    联合省选2021游记
    高维 FWT 学习笔记
    Unicode简介
    mac安装brew
    原生JS实现分页跳转
    Kubernetes Pod Probes 探针解析
    Kubernetes Secrets
    Kubernetes Container lifecycle hooks
    个人作业1——四则运算题目生成程序(基于java)
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/10587294.html
Copyright © 2020-2023  润新知