Question
665. Non-decreasing Array
Solution
题目大意:
思路:当前判断2的时候可以将当前元素2变为4,也可以将上一个元素4变为2,再判断两变化后是否满足要求。
Java实现:
public boolean checkPossibility(int[] nums) {if (nums == null || nums.length < 3) return true;int count = 0;// 判断前2个if (nums[1] < nums[0]) {nums[0] = nums[1] - 1;count++;}for (int i = 2; i < nums.length; i++) {if (nums[i] < nums[i - 1]) {count++;if (nums[i - 2] <= nums[i] - 1) {nums[i - 1] = nums[i] - 1;} else if (i == nums.length -1 || nums[i + 1] >= nums[i - 1] + 1) {nums[i] = nums[i - 1] + 1;} else {return false;}}}return count < 2;
}
别人实现:
public boolean checkPossibility(int[] nums) {int cnt = 0; //the number of changesfor(int i = 1; i < nums.length && cnt<=1 ; i++){if(nums[i-1] > nums[i]){cnt++;//modify nums[i-1] of a priorityif(i-2<0 || nums[i-2] <= nums[i])nums[i-1] = nums[i];else nums[i] = nums[i-1]; //have to modify nums[i]}}return cnt<=1;
}