LeetCode-Easy-Java-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.


最初的解决思路就是判断是否出现了两对非递增数,如果出现则返回false,出现了一对非递增数后,则需要判断改变该数后,该数与其前后还是否满足递增关系。

例如 [3,3,2,4],出现的第一对非递增数是[3,3,2,4],可以选择将3变2,成为[3,2,2,4],也可以选择将2变为3[3,3,3,4]。第一种变化后,序列不满足递增,而第二种变化满足。因此变化后的判断逻辑为:

设非递增数对为[a,b],即a>b,若将a变换为b,则判断b是否小于a前一个数;若将b变换为a,则判断a是否大于b后一个数。只有这样才能保证变换后数组仍为递增数组。

代码如下:

public boolean checkPossibility(int[] nums) {
        int count=0;
        int position=0;
        if(nums.length==1){
            return true;
        }
        for(int i=0;i<nums.length-1;i++){
            if(nums[i]<=nums[i+1]){
                continue;
            }else {
                count++;
                position=i;
                if(count>=2){
                       System.out.println("False");
                      System.out.println("You can't get a non-decreasing array by modify at most one element");
                    return false;
                }
            }
        }
        if(position-1<0||position+2>nums.length-1)//若被变换的数前面也没有,后面也没有则直接返回true{
            return true;
        }else if(position-1>=0&&nums[position-1]<=nums[position+1]){
            return true;
        }else if(position+2<=nums.length-1&&nums[position]<=nums[position+2]){
            return true;
        }
        return false;
    }

下面是LeetCode上的优秀代码:

 public boolean checkPossibility(int[] nums) {
        int channum = 0;
        for(int i=1;i<nums.length;i++){
            if(nums[i]<nums[i-1]){
                channum++;
                if(i>1&&nums[i]<nums[i-2]){ //这条语句用于判断b是否小于a前面的数,若小于则将b变换为a
                    nums[i] = nums[i-1];
                } 
            }
            if(channum==2) return false;
        }
        return true;
    }

更多算法知识点 关注FunctionY csdn博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值