The difficulty of this question is easy, and the current pass rate is 20.3%
topic:
Given an array 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 array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
Note: The n belongs to [1, 10,000].
The gist of the title is to give a list of n numbers, can you point out that by modifying a number, this list can be turned into an increasing sequence.
Idea:
Use a bool variable to determine whether the number has been modified. There are roughly the following ways to modify the number:
1. The title gives [4, 2, 3], because the number to be modified is the first number, so directly change the first number to be the same as the second number. But 2.[ 2,4,3
], in addition to the first number, for convenience, you can directly change the number to be modified to the previous number, such as [2,2,3].
3.[1,4,2,3], if you change 2 to 4 at this time, you need to change 3 to 4 to return to Flase. But the best way is to change 4 to 1 or 2. Therefore, the method is modified to compare with the first two numbers. If it is [1,4,2], the middle number is modified, otherwise the last number is modified.
Code:
class Solution:
def checkPossibility(self, nums):
judge = False
n = len(nums)
for i in range (1,n):
if nums[i] < nums[i-1]:
if judge:
return False
if i==1 or nums[i-2] <= nums[i]:
nums[i-1] = nums[i]
else:
nums[i] = nums[i-1]
judge = True
return True
Complexity Analysis:
Since there is only one for loop, the time complexity is T(n)=O(n).
submit: