[leetcode-665-Non-decreasing Array]

检查数组是否可变成非递减
本文介绍了一个算法问题的解决方案,即判断一个整数数组通过修改最多一个元素是否可以变成非递减序列。文章提供了详细的逻辑分析及C++实现代码。

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

思路:

考虑数组中逆序发生的次数,如果cnt>=2,返回false。如果cnt==1的话需要判断一下。


比如 xxx 5 3 7 xx  发生了一次逆序  5比7小 只需将3调整为7就可以了 
还有就是比如 xxxxx2725xxx 从7那下降了 然后从2后上升了 但是此时把7改成2就可以啦
这个就是属于if (nums[index - 1] <= nums[index + 1])return true;


就是先下降后上升 如果上升的更高 那就改一次就行了

但是如果没更高  那就试试把左边的也下降一下 看满足条件不 如果满足就true 否则false

bool checkPossibility(vector<int>& nums)
{
    if (nums.size() <=2)return true;
    int  cnt = 0,index =0;
    for (int i = 0; i < nums.size()-1;i++)
    {
        if (nums[i]>nums[i + 1])
        {
            cnt++;
            index = i;//逆序发生位置
        }
    }    
    if (cnt == 0)return true;
    if (cnt == 1)
    {
        if (index == 0 || index == nums.size() - 1)return true;
        if (nums[index] <= nums[index + 2])return true;
        if (nums[index - 1] <= nums[index + 1])return true;
        return false;
    }    
    return false;
}

 

转载于:https://www.cnblogs.com/hellowooorld/p/7439947.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值