LeetCode#665: Non-decreasing Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/83268282

Description

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).

Example

Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note

  • The n belongs to [1, 10,000].

Solution

此题主要要分清楚两种情况:

用[]括起来的代表下标i的元素,此时nums[i] < nums[i-1]
case1: 1,1,3,4,[2],5,6
case2: 1,1,2,4,[2],3,4

在第一种情况中,nums[i] < nums[i-2],因此要把nums[i-1]的值赋给nums[i],得到1,1,3,4,[4],5,6;在第二种情况中,nums[i] > nums[i-2],因此说明出现问题的是nums[i-1],因此将nums[i]赋给nums[i-1],得到1,1,2,2,[2],3,4。凡是修改了值就将mod变量减一,如果mod等于0了则返回false。

class Solution {
    public boolean checkPossibility(int[] nums) {
        if(nums.length == 1)
        	return true;
        
        int mod = 1;
        for(int i = 1; i < nums.length; i++) {
        	if(nums[i] < nums[i-1]) {
        		if(mod == 0) return false;
        		if(i - 2 < 0 || nums[i-2] <= nums[i])
        			nums[i-1] = nums[i];
        		else 
        			nums[i] = nums[i-1];
        		mod--;
        	}
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/83268282