首页 > 其他 > 详细

665. Non-decreasing Array

时间:2020-03-15 15:21:18      阅读:47      评论:0      收藏:0      [点我收藏+]

问题:给定数组中,能否最多修改一个数,使得数组成为非减数组,即对数组中任意相邻两数: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 };

 

665. Non-decreasing Array

原文:https://www.cnblogs.com/habibah-chang/p/12497362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!