C#LeetCode刷题之#665-非递减数列（ Non-decreasing Array）

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

Input: [4,2,3]

Output: True

Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

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

```public class Program {

public static void Main(string[] args) {
int[] nums = null;

nums = new int[] { 4, 2, 3 };
var res = CheckPossibility(nums);
Console.WriteLine(res);

}

private static bool CheckPossibility(int[] nums) {
//当发现逆序时，根据更后面1个值决定把当前值变成后面的
//还是把后面的值变成前面的，最后判定数组是否升序即可
for(int i = 0; i < nums.Length - 1; i++) {
if(nums[i] > nums[i + 1]) {
if(i + 2 < nums.Length && nums[i + 2] < nums[i]) {
nums[i] = nums[i + 1];
} else {
nums[i + 1] = nums[i];
}
return IsSortedArray(nums);
}
}
return true;
}

private static bool IsSortedArray(int[] nums) {
//判断数组是否升序
for(int i = 0; i < nums.Length - 1; i++) {
if(nums[i] > nums[i + 1]) return false;
}
return true;
}

}```

`True`