HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
코딩테스트 스터디
코딩테스트 스터디
/
Non-decreasing Array

Non-decreasing Array

Link
https://leetcode.com/problems/non-decreasing-array/
Deadline
Jul 3, 2022
Status
Archived
Type
Array

문제

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

풀이

은찬
const checkPossibility = (nums) => { let isModified = false; for(let i = 1; i < nums.length; i++){ if(nums[i] < nums[i - 1]){ if(isModified){ return false; } else{ isModified = true; } if(i === 1 || nums[i - 2] <= nums[i]){ nums[i - 1] = nums[i]; } else{ nums[i] = nums[i - 1]; } } } return true; };
 
재영
/** * @param {number[]} nums * @return {boolean} */ var checkPossibility = function(nums) { let cnt = 0; if (nums[1] && nums[0] > nums[1]) { cnt += 1; nums[0] = nums[1] - 1; } for (let i = 1; i < nums.length; i += 1) { if (nums[i] > nums[i + 1]) { // decreasing if (cnt === 1) return false; cnt += 1; // cnt = 1 if (nums[i + 1] < nums[i - 1]) { // i - 1이 만약에 i + 1보다 크다는 것 = decreasing nums[i + 1] = nums[i] // 최소한 i + 1은 i만큼은 되어야 증가하거나 같은 배열로 존재할 수 있음. } else { nums[i] = nums[i - 1] // v자로 됐을 경우에 -> i - 1로 해줌으로써 _/ } } } return true; };
효성
var checkPossibility = function(nums) { let editCnt = 0; for(let i = 1; i < nums.length; i++) { if(nums[i] < nums[i - 1]) { if(editCnt++ || i < nums.length - 1 && nums[i - 2] > nums[i] && nums[i + 1] < nums[i -1]) { return false; } } } return true; };