Given an array nums
with n
integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1]
holds for every i
(0-based) such that (0 <= i <= n - 2
).
Example 1:
Input: nums = [4,2,3] Output: true Explanation: You could modify the first4
to1
to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1] Output: false Explanation: You can't get a non-decreasing array by modify at most one element.
Constraints:
n == nums.length
1 <= n <= 104
-105 <= nums[i] <= 105
题目链接:https://leetcode.com/problems/non-decreasing-array/
题目大意:给一个数组,最多改变一个数字问能否使其变为单调不减
题目分析:遇到一组连续递减时,假设nums[i] < nums[i - 1],有两种方案:
1. 将nums[i]变大,保证单调不减的最优方案是将nums[i-1]赋给nums[i]
2. 将nums[i-1]变小,保证单调不减的最优方案是将nums[i - 2]赋值给nums[i - 1],若i等于1,则赋值为nums[i]即可
不妨先选方案2,修改完后需要判断修改的值是否小于等于nums[i],如果不是则只能通过方案1,若之后还存在递减则无法完成
0ms,时间击败100%
class Solution {
public boolean checkPossibility(int[] nums) {
int n = nums.length;
if (n < 3) {
return true;
}
boolean change = false;
for (int i = 1; i < n; i++) {
if (nums[i] < nums[i - 1]) {
if (!change) {
change = true;
int tmp = i - 2 >= 0 ? nums[i - 2] : nums[i];
if (tmp > nums[i]) {
nums[i] = nums[i - 1];
} else {
nums[i - 1] = tmp;
}
} else {
return false;
}
}
}
return true;
}
}