[leetcode]665. Non-decreasing Array

[leetcode]665. Non-decreasing Array


Analysis

ummmm~—— [ummmm~]

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).
遍历数组,只能找到一组nums[i]

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81066177