PROBLEM:
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 first4
to1
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].
SOLVE:
/*
找到中心步骤为:用一个变量记录前一个值former(一开始不存在但需要比较,设为-1),比较当前值now和后一个值next大小。
如果递减{则判断去掉now是否可行,是则改变now和next的值;否则去掉next并直接改变next的值},
否则former=now;now=next;next=*(++iter)。只能去掉一次,用一个变量记录就行了。
*/
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
bool tag=true;
auto iter=nums.begin()+1;
int former=-1,now=*(iter-1),next=*iter; //数组中都为整数,否则former初始化为INT_MIN
while(iter!=nums.end()){
if(tag&&now>next){
tag=false;
if(former>next)
next=*(++iter);
else{
now=next;
next=*(++iter);
}
}
else if(now>next)
return false;
else{
former=now;
now=next;
next=*(++iter);
}
}
return true;
}
};
用下标可能会使得程序更加简洁,但是速度没迭代器快,我使用迭代器进行求解