• 665. Non-decreasing Array


    Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.

    We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

    Example 1:

    Input: nums = [4,2,3]
    Output: true
    Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
    

    Example 2:

    Input: nums = [4,2,1]
    Output: false
    Explanation: You can't get a non-decreasing array by modify at most one element.
    

    Constraints:

    • n == nums.length
    • 1 <= n <= 104
    • -105 <= nums[i] <= 105
    class Solution {
        public boolean checkPossibility(int[] nums) {        
            // corner case
            if(nums == null || nums.length <= 1) return true;
            
            // the count of continuous non-decreasing sub-array
            int count = 1;
            int index = 0;
            
            int n = nums.length;        
            for(int i = 1; i < n; i++){
                if(nums[i] < nums[i - 1]){
                    index = i;
                    count++;
                }
            }
            
            if(count == 1) return true;
            if(count == 2){ 
                // if the discord happens at start or end position, we can modify
                // it to match the condition
                if(index == 1 || index == n - 1) return true;
                
                // if in the middle, we modify nums[index - 2]
                // index - 2, (index - 1, index) , index + 1
                if(nums[index + 1] >= nums[index - 1] || nums[index] >= nums[index - 2]) {
                    return true;
                }
                return false;
            }
            
            return false;
        }
    }

    https://leetcode.com/problems/non-decreasing-array/discuss/106826/JavaC%2B%2B-Simple-greedy-like-solution-with-explanation

    用count来表示non decreasing的subarray的数量,如果是1直接return true,如果大于2直接返回false。

    如果是2,说明是两段。分两种情况,第一种要求转折点index有index + 1 >= index - 1, 或者index >= index - 2.

  • 相关阅读:
    性格-汉语-词语:坚忍
    汉语-词语:坚强
    品质-汉语-成语:坚持不懈
    was系统错误日志大量出现标识符缺失
    【iOS】UIWebView的HTML5扩展之canvas篇
    OA权限树搭建 代码
    linux下的环境文件设置说明
    怎样把多个Android Project打包成一个APK
    nyoj43 24 Point game(DFS)
    【西祠日志】【07】努力努力,找资料,思考,怎么做asp图片上传
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14730966.html
Copyright © 2020-2023  润新知