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 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].
題意:判斷給定的序列是否可以最多隻改變一個數字就能得到非遞減序列。
主要難點是分析所有可能的情況,程序必須要知道最小改動的數字位置是什麼地方。
當遇到遞減的情況(A[i]< A[i-1])時需要進行修改,但是存在兩種情況,1)改動A[i],2)改動A[i-1]。
如果A[i-2]<=A[i],則改動A[i],否則改動A[i-1],這樣不會影響後面數據的判斷。
代碼如下:
class Solution {
public boolean checkPossibility(int[] nums) {
boolean modified=false;
for(int i=1;i<nums.length;i++){
if(nums[i]<nums[i-1])
{
if(modified)
return false;
if(i<2 || nums[i-2]<=nums[i])
nums[i-1]=nums[i];
else
nums[i]=nums[i-1];
modified=true;
}
}
return true;
}
}