给定一个包含 n 个整数的数组,你的任务是检测在改变至多一个元素的情况下,它是否可以变成不下降的。
我们定义一个数组是不下降的,如果 array[i] <= array[i + 1] 对于每一个 i (1 <= i < n) 都成立。
样例1:
输入: [4,2,3]
输出: True
解释: 你可以把第一个4修改为1从而得到一个不下降数组。
样例2:
输入: [4,2,1]
输出: False
解释: 你无法得到一个不下降数组,在修改至多一个元素的情况下。
class Solution {
public:
/**
* @param nums: an array
* @return: if it could become non-decreasing by modifying at most 1 element
*/
bool checkPossibility(vector<int> &nums) {
// Write your code here
int judge=0;
int len=nums.size();
int pos=0;
for (int i = 1; i < len; i++) {
/* code */
if(nums[i-1]>nums[i])
{
pos=i;
judge++;
}
}
if(judge==0) return true;
else if(judge>1) return false;
return pos==1||pos==len-1||nums[pos-2]<=nums[pos]||nums[pos-1]<=nums[pos+1];
}
};