- Non-decreasing Array
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].
#author ncepu_David
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
"""
当发生递减时:比如4 2 3 我们发现4>2,一般我们为了实现非递减,可以把4变成2(变小),也可以2变成4(变大),两种方式尽量选第一种(变小),因为第二种方法可能导致后面的情况又出现递减。
再考虑其他情况,比如 -1 4 2 3 和 3 4 2 3 我们发现第一个数组中4可以变成2但是第二个数组中4不能变成2,只能考虑将2变成4(当然第二个数组不满足非递减,2变成4后:4 3又递减了)。问题的关键在于4左右两个数的大小关系。
综上:我们只要用一个flag记录发生递减时交换的次数,只能交换一次,当第二次发生递减时就不用做交换了,直接根据判断False
"""
flag=False #修改标志位,最多只可以改一次
for i in range(len(nums)-1):
if nums[i]>nums[i+1]: #问题的关键就是找到递减位
if(flag): #最多只可以改一次,初值是False,改过一次就是True,因此实现最多改一次
return False
else:
if(i==0 or nums[i+1]>nums[i-1]): #当递减位是第一个值或者递减位右边的值大于左边的,则将递减位变小
nums[i]=nums[i+1]
else: #反之,递减位右边的值小于左边的,则将递减位右边的值变大。
nums[i+1]=nums[i]
flag=True
return True