665. Non-decreasing sequence-Java

Here is an integer array of length n. Please judge whether the array can be turned into a non-decreasing sequence when one element is changed at most.

We define a non-decreasing number sequence like this: For all i (0 <= i <= n-2) in the array, nums[i] <= nums[i + 1] is always satisfied.

Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You can make it a non-decreasing sequence by changing the first 4 to 1.

Example 2:
Input: nums = [4,2,1]
Output: false
Explanation: You cannot change one element to a non-decreasing sequence.

Source: LeetCode
Link: https://leetcode-cn.com/problems/non-decreasing-array

method one:

  1. Use count to record the number of element changes
  2. Traverse the array nums
  3. If nums[i-1]> nums[i] , you need to update nums[i] or nums[i-1] , and whether to update depends on nums[i-2]
  4. If nums[i-2]> nums[i] , then assign the value of nums[i-1] to nums[i] , otherwise assign the value of nums[i] to nums[i-1]
  5. When it is judged that count is greater than 1 , stop the loop and return false
public static boolean checkPossibility(int[] nums) {
    
    
    boolean flag = true;
    int count = 0;
    for (int i = 1; i < nums.length; i++) {
    
    
        if (nums[i - 1] > nums[i]) {
    
    
            if (i >= 2 && nums[i - 2] > nums[i]) {
    
    
                nums[i] = nums[i - 1];
            } else {
    
    
                nums[i - 1] = nums[i];
            }
            count++;
        }
        if (count > 1) {
    
    
            flag = false;
            break;
        }
    }
    return flag;
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/108045892