首页 > 其他 > 详细

[leetcode-665-Non-decreasing Array]

时间:2017-08-27 12:36:53      阅读:294      评论:0      收藏:0      [点我收藏+]

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;
}

 

[leetcode-665-Non-decreasing Array]

原文:http://www.cnblogs.com/hellowooorld/p/7439947.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!