当前位置: 代码迷 >> 综合 >> LeetCode 665. Non-decreasing Array
  详细解决方案

LeetCode 665. Non-decreasing Array

热度:62   发布时间:2023-10-09 14:17:59.0

Non-decreasing Array


题目描述:

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].


题目大意:

给定一个数组,判断是否可以最大只改变一个数的值,就可以让该数组的元素呈非递减序列。

遍历整个数字,如果当前数字比前面的数字小,那么这个数字是一定要改变的。需要考虑的是,把当前的数字改成多少才合适。

因为要得到的序列是非递减的,意味着相邻的元素可以是相同的,那么我们就可以将需要改变的数字改为前面的那个数字,当然我们也可以把前面的那个数字改成当前的这个数字。

当决策有两种的时候,我们只需要考虑其中一种较为简单的情况需要符合的条件。条件之外就是另一种情况。

这里我们考虑把前面的数字变成当前的数字的情况,当前面的数字再前面没有数字,那么无疑改前面的数字是最好的,不会影响后面。如果前面的数字再前面还有数字,并且要是小于关系,那么改前面这个数字也是对后面没影响的。

我们只要按照这种方法进行数字的修改,直至遍历完成,如果修改次数小于等于1,那么返回true,否则返回false。


题目代码:

class Solution {
public:bool checkPossibility(vector<int>& nums) {int cnt = 0;for(int i = 1; i < nums.size() && cnt <=1; i++){if(nums[i-1] > nums[i]){cnt++;if(i-2 < 0 || nums[i-2] <= nums[i])nums[i-1] = nums[i];elsenums[i] = nums[i-1];}}return cnt <= 1;}
};


  相关解决方案