问题描述:
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).
示例:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4
to 1
to get a non-decreasing array.
Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element.
问题分析:
统计出现array[i] > array[i + 1] 该条件的次数,如果大于2,则返回false,如果等于0,则返回true,其他情况分别作讨论即可。
过程详见代码:
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
bool modified = false;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] < nums[i - 1]) {
if (modified) return false;
(i - 2 < 0 || nums[i - 2] <= nums[i]) ? nums[i - 1] = nums[i] : nums[i] = nums[i - 1];
modified = true;
}
}
return true;
}
};