最开始想法比较简单,统计当前数字,如果比前一个数字小,那么记录一次,如果出现次数大于1那么返回false.

class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        int size = nums.size(),cnt = 0;
        for(int i = 1;i < size;i++) 
        {
            if(nums[i] < nums[i-1])
            {
                cnt++;
                if(cnt > 1) return false;
            }
        }
        return true;
    }
};

存在无法处理的用例:

320 / 335 test cases passed.
Status: Wrong Answer
Submitted: 7 minutes ago
Input : [3,4,2,3]
Output : true
Expected : false

这里正确的解法,当nums[i] <nums[i-1]时将nums[i-1]更新为nums[i],如果此时nums[i]<nums[i-2]也成立,这个时候就不能更改nums[i-1]和nums[i-2]了,可以更改一次nums[i].

class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        int cnt = 0;
        for(int i = 1;i < nums.size() && cnt <= 1;i++)
        {
            if(nums[i] < nums[i-1])
            {
                cnt++;
                if(i-2>=0 && nums[i] < nums[i-2])
                    nums[i] = nums[i-1];
                else
                    nums[i-1] = nums[i];
            }
        }
        
        return cnt <=1;
    }
};

运行效率:

Runtime: 20 ms, faster than 97.66% of C++ online submissions for Non-decreasing Array.
Memory Usage: 27.1 MB, less than 66.67% of C++ online submissions for Non-decreasing Array.