Fork me on GitHub

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

思路:

考虑数组中逆序发生的次数,如果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;
}

 

posted @ 2017-08-27 11:33  hellowOOOrld  阅读(573)  评论(0编辑  收藏  举报