본문 바로가기
LeetCode/Problems

LeetCode 665. Non-decreasing Array

by 벤진[Benzene] 2020. 6. 18.

Problem:

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

 

-Summary-

1. Find a position where modification occur. [nums[i] > nums[i+1]]

2. If there is more than 1 case where current number is bigger than next number, automatically return False.

3. Otherwise, we have only below cases left to analyze.

처음에 풀어보다가, [3,4,2,3]의 case에서 막혀서 솔루션의 도움을 받아 풀었다. 오늘도 문제를 풀면서 많이 배운다. 파이썬의 or 은 앞에서부터 차례대로 계산을 하기 때문에 앞에서 True 가 나오면 뒤에 계산을 하지 않기때문에 index out of range error가 발생하지 않는다.

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글