題目
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).
給定一個整數數組,判定是否最多修改一個位置上的數字就可以讓這個數組變成遞增數組(包含等號)。
解析
基本思想是貪心算法,碰到一個不符合要求的就恢復一個,如果修復次數多于一次則返回false
需要處理的就是發生后一個數小于前一個數的部分,比如 [3 4 2] 中 4 和 2是沖突的。
標記為 ai-2, ai-1, ai,發生沖突后可以用兩種方法進行修復(肯定能修復):
- 如果ai-2 > ai,則需要做ai = ai-1的修改,如 3 4 2
- 否則做ai-1=ai的修改,因為局部修改可以防止后面的出現問題,如1 4 2 3
代碼
public boolean checkPossibility(int[] nums) {
if(nums == null || nums.length == 0) return false;
int cnt = 0; //修復次數
for(int i = 1; i < nums.length && cnt <= 1; ++i){
if(nums[i-1] > nums[i]){
cnt ++;
//做出修復
if(i - 2 >= 0 && nums[i-2] > nums[i]){ //這種情況只能對nums[i]進行修復
nums[i] = nums[i-1];
}else{ //一般選擇對nums[i-1]進行修復
nums[i-1] = nums[i];
}
}
}
return cnt <= 1;
}