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


    题目标签:Array

      题目给了我们一个nums array, 只允许我们一次机会去改动一个数字,使得数组成为不递减数组。可以实现的话,return true;不行的话,return false。

      这个题目关键在于,当遇见一个 nums[i] > nums[i+1] 的情况,我们是把 nums[i]降为nums[i+1] 还是 把nums[i+1]升为nums[i]。

      如果可行的话,当然是选择优先把 nums[i]降为nums[i+1],这样可以减少 nums[i+1] > nums[i+2] 的风险。

      来看一下两种情况:

      a. 1 3 5 4 6 7  -->  1 3 4 4 6 7

        当遇到5 > 4 的情况,这里因为4比5 之前的所有数字都大,所以可以把5 降为4。

      b. 1 4 5 3 6 7  -->  1 4 5 5 6 7

        当遇到5 > 3 的情况,这里3比5之前的4小,所以没有选择,只能把3 升为5。

      

      当需要第二次改动的时候,可以直接返回false,不需要把剩下的array走完。

    Java Solution:

    Runtime beats 89.68% 

    完成日期:10/20/2017

    关键词:Array

    关键点:了解有2种改动情况和优先级

     1 class Solution 
     2 {
     3     public boolean checkPossibility(int[] nums) 
     4     {
     5         boolean modified = false;
     6         
     7         for(int i=0; i<nums.length; i++)
     8         {
     9             if(i+1 < nums.length && nums[i] > nums[i+1])
    10             {
    11                 if(modified) // if modified a number already
    12                     return false;
    13                 else // if it is first time to modify a number
    14                 {
    15                     if(i-1 < 0 || nums[i+1] >= nums[i-1]) // if nums[i+1] is larger or equal all numbers before nums[i]
    16                         nums[i] = nums[i+1]; // change nums[i] as same as nums[i+1]
    17                     else // if nums[i+1] is not larger than all numbers before nums[i]
    18                         nums[i+1] = nums[i]; // change nums[i+1] as same as nums[i]
    19                     
    20                     modified = true;
    21                 } 
    22             }
    23         }
    24         
    25         return true;
    26         
    27     }
    28 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

  • 相关阅读:
    Spring boot3之整合HTML
    Spring boot4之数据校验
    Spring boot5之整合mybatis
    Spring boot6之整合Spring Data JPA
    Spring boot7之整合Spring Data Redis
    Spring boot8之整合Spring Security
    sqlmap从入门到精通-第七章-7-11 绕过WAF脚本-informationschemacomment.py&least.py
    系统提权-各种反弹shell使用
    Vulnhub-靶机-SpyderSec: Challenge
    sqlmap从入门到精通-第七章-7-10 绕过WAF脚本-ifnull2casewhenisnull.py&ifnull2ifisnull.py
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7703350.html
Copyright © 2020-2023  润新知