--- modify a greedy strategy to become non-decreasing number of array

Modify become a non-decreasing number of array

665. Non-decreasing Array (Easy)

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Subject description:

  Determine whether an array can be modified only become a non-decreasing number of arrays.

Analysis of ideas:

  Appears nums [i] <nums [i-1], the need to consider which of the array to be modified, such that this modification allows the array before the array i becomes non-decreasing, and does not affect the subsequent operation. Priority nums [i-1] = nums [i], because if you modify nums [i] = nums [i-1], then nums [i] this number becomes large, there may be more than nums [i + 1 ] large, thus affecting the subsequent operation. Another case is nums [i] <nums [i-2], modify nums [i-1] = nums [i] array can not be nondecreasing array can be modified nums [i] = nums [i-1 ].

Code:

public boolean checkPossibility(int []nums){
    int cnt =0;
    for(int i=1;i<nums.length&&cnt<2;i++){
        if(nums[i]>=nums[i-1])
            continue;
        cnt++;
        if(i-2>=0&&nums[i-2]>nums[i]){
            nums[i]=nums[i-1];
        }else{
            nums[i-1]=nums[i];
        }
    }
    return cnt<=1;
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11105942.html