Non-decreasing Array
Description
Given an array nums
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 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:
1 <= n <= 10 ^ 4
- 10 ^ 5 <= nums[i] <= 10 ^ 5
Solution(javascript)
/** 1. Monotone Stack 不行
* 2. 两种可能,改当前的数或者改前一个数
* @param {number[]} nums
* @return {boolean}
*/
const checkPossibility = function (nums) {
const check = (arr = []) => {
for (let i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) {
return false
}
}
return true
}
for (let i = 0; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) {
const temp = nums[i]
nums[i] = nums[i - 1]
if (check(nums)) {
return true
}
nums[i] = temp
nums[i - 1] = nums[i]
return check(nums)
}
}
return true
}