问题:给定数组中,能否最多修改一个数,使得数组成为非减数组,即对数组中任意相邻两数:nums[i] <= nums[i+1]
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].
解决方法:
依次判断数字是否>前一个数
tip:[3,4,2,3] [↗︎↘︎↗︎]类似这种,两个上升中只有一个下降,可能会导致错误
nums[0] 3>2 nums[2]
由于题目限定与最多改一个,则再判断i-2是否<=i,即可
若不满足,则使 nums[i] = nums[i-1] 增大i的值,让下一轮判断 i 和 i+1 的时候,count++能够再执行一次
参考代码:
1 class Solution { 2 public: 3 bool checkPossibility(vector<int>& nums) { 4 int count=0; 5 for(int i=1; i<nums.size(); i++){ 6 if(count>1)return false; 7 if(nums[i]<nums[i-1]){ 8 count++; 9 if(i>1 && nums[i-2] >nums[i]) nums[i]=nums[i-1]; 10 else nums[i-1]=nums[i]; 11 } 12 } 13 if(count>1)return false; 14 return true; 15 } 16 };