【Super Easy】solve this question in 1 min [Java]


  • 0
    P
    /* E.g:    [1,3,2] -> find 'first' decreasing "3,2",  then we have 2 ways to fix it:
       way A:  [1,2,2]
       way B:  [1,3,3]
       if (one of A, B is non-decreasing), result = true;
       else,                               result = false;
     */
    
    public boolean checkPossibility(int[] nums) {
        int[] A = nums.clone(),   B = nums.clone();
        boolean a = true,         b = true;
        
        for (int i = 0; i < nums.length - 1; i++) 
            if ( nums[i] > nums[i+1]) {
                A[i]   = nums[i+1];
                B[i+1] = nums[i];
                break;
            }
    
        for (int i = 0; i < nums.length - 1; i++) {
            if ( A[i] > A[i+1])   a = false;
            if ( B[i] > B[i+1])   b = false;
        }
             
        return a || b;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.