Non-decreasing Array
Description
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.Solutions
My solution
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int i = 0, n = nums.size();
while(i + 1 < n && nums[i] <= nums[i + 1]) ++i;
// i == n - 1, the whole array is non-decreasing
// i == n - 2, we can change the last element to make the array non-decreasing.
if(i >= n - 2) return true;
int j = n - 1;
// no need to check j > 0 because
// nums[i] > nums[i + 1]
// so the while loop must terminate
while(nums[j - 1] <= nums[j]) --j;
// if j - i > 1, at least two reverse pairs
// i.e., (nums[i], nums[i + 1]) and (nums[j - 1], nums[j])
if(j - i > 1) return false;
// i + 1 == j
// only one reverse pair
// check if it's possible to change either nums[i] or nums[j]
// to make the array non-decreasing
return i == 0 || nums[i - 1] <= nums[j] || nums[i] <= nums[j + 1];
}
};Solution 1
Solution 2
Last updated