Leetcode 665. Non-decreasing Array(Easy)
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].
/* 一开始想的有点简单,直接只是判断有多少个不符合的位置,并没有修复并检查修复后是否满足条件 所以 出现 3, 4, 2, 3的case就不行了 其实主要分两种情况: 2, 4, 2, 3 3, 4, 2, 3 判断当前的值是否比前一个值小,如果小的话, 再判断是否比 前前一个值 要小, 如果小,改变当前的值 使得其跟前一个值一样大,如果大,改变前一个值,使得它跟当前的值一样大。 */ class Solution { public: bool checkPossibility(vector<int>& nums) { int len = nums.size(); int count = 0; // if (len == 0) return false; for (int i = 1; i < len; i++){ if (nums[i] < nums[i - 1]){ count ++; if (count > 1){ return false; } if (nums[i] < nums[i - 2] && (i - 2) >= 0){ nums[i] = nums[i - 1]; } else{ nums[i - 1] = nums[i]; } } } return true; } };