码迷,mamicode.com
首页 > 编程语言 > 详细

665. Non-decreasing Array只允许修改一位数的非递减数组

时间:2018-04-21 17:43:28      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:程序   pac   空间   else   length   结果   输出   图片   .com   

[抄题]:

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.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么改啊

[一句话思路]:

既然只允许修改一位,“前天”是否异常,决定了应该修改“昨天”还是“今天”

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

技术分享图片

[一刷]:

  1. 必须要有“昨天”异常的前提才有后续的操作。所以要把“昨天”之后的全都括起来

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

头回见:既然只允许修改一位,“前天”是否异常,决定了应该修改“昨天”还是“今天”

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

技术分享图片
class Solution {
    public boolean checkPossibility(int[] nums) {
        //cc
        if (nums == null || nums.length == 0) {
            return false;
        }
        
        //ini
        int count = 0;
        
        //for loop
        for (int i = 1; i < nums.length && count <= 1; i++) {
            if (nums[i - 1] > nums[i]) {count++;
            if (i - 2 < 0 || nums[i - 2] < nums[i]) {
                nums[i - 1] = nums[i];
            }else {
                nums[i] = nums[i - 1];
            }}
        }
        
        //return count <= 1
        return count <= 1;
    }
}
View Code

 

665. Non-decreasing Array只允许修改一位数的非递减数组

标签:程序   pac   空间   else   length   结果   输出   图片   .com   

原文地址:https://www.cnblogs.com/immiao0319/p/8901802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!