/** * references: * https://www.cnblogs.com/grandyang/p/7565424.html * @brief The Solution class * Given an array with n integers, your task is to check if it * could become non-decreasing by modifying at most 1element. 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]. 这道题给了我们一个数组,说我们最多有1次修改某个数字的机会,问能不能将数组变为非递减数组。 题目中给的例子太少,不能覆盖所有情况,我们再来看下面三个例子: 4,2,3 -1,4,2,3 2,3,3,2,4 * */ /** * @总结: * 1,通过举例子覆盖所有用例,从而辅助写代码 */ class Solution{ public: bool checkPossibility(vector<int>& nums){ int cnt = 1,n = nums.size(); for(int i = 1; i < n; i++){ if(nums[i] < nums[i-1]){ if(cnt == 0) return false; if(i == 1 || nums[i] >= nums[i-2]) nums[i-1] = nums[i]; else nums[i] = nums[i-1]; --cnt; } } return true; } };
怕什么真理无穷,进一寸有一寸的欢喜。---胡适