zoukankan      html  css  js  c++  java
  • 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]
                    
  • 相关阅读:
    float保留指定位数的小数
    springmvc中拦截器的使用
    springmvc文件上传
    spring注入
    mybatis动态代理
    2017《JAVA技术》预备作业02 计科1502 郎春雨
    2017《JAVA技术》预备作业01 计科1502 郎春雨
    字符串占位符的使用
    Pyenv虚拟环境的创建(虚拟机)
    Git的基本使用
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/10587294.html
Copyright © 2011-2022 走看看