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)
- 정수가 n 인 배열의 숫자가 주어지면 최대 1 개의 요소를 수정하여 감소하지 않을 수 있는지 확인
- nums [i] <= nums [i + 1]이 (0 <= i <= n-2)와 같이 모든 i (0 기반)에 대해 유지되는 경우 배열이 감소하지 않는 것으로 정의
example
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 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.
// 초기코드
/**
* @param {number[]} nums
* @return {boolean}
*/
var checkPossibility = function(nums) {
};
/**
* @param {number[]} nums
* @return {boolean}
*/
var checkPossibility = function(nums) {
let changed = false;
for(let i = 1; i < nums.length; i++) {
if(nums[i] < nums[i-1]) {
if(changed) {
return false;
}
if(nums[i-2] > nums[i]) {
nums[i] = nums[i-1];
changed = true;
} else {
nums[i-1] = nums[i];
changed = true;
}
}
}
return true;
};
/**
* @param {number[]} nums
* @return {boolean}
*/
var checkPossibility = function(nums) {
for(let i = 1; i < nums.length; i++) {
if(nums[i] < nums[i-1] ) {
if(nums[i-2] > nums[i]) {
nums[i] = nums[i-1];
} else {
nums[i-1] = nums[i];
}
break;
}
}
if(!nums.some((num, index) => num > nums[index+1])){
return true;
} else {
return false;
}
};