zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    20199108 2019-2020-2 《网络攻防实践》第8周作业
    20199108 2019-2020-2 《网络攻防实践》第7周作业
    攻防作业报告提交
    Spring整合HBase
    基于注解的Spring AOP示例
    Spring AOP基本概念
    在RichFaces中使用Facelets模板
    算法导论读书笔记(19)
    算法导论读书笔记(18)
    算法导论读书笔记(17)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7703350.html
Copyright © 2011-2022 走看看