665. 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].
思路:
琢磨了半天才有了一个勉强可行的思路,就是复制2个数组(a,b)出来,只要碰到 nums[i]>nums[i+1] 的情况,前一个(a)直接删除 nums[i] 再比较删除后的数组是否是已经排序好的(a 是不是等于 sorted(a) ),后一个数组(c)直接删除 nums[i+1] 再比较删除后的数组是否是已经排序好的(c 是不是等于 sorted(c) ),只要二者之间有一个是已经排序好的就返回 True 否则 返回 False。
(刚开始就是想单纯比较 nums[i]>nums[i+1] 时,如果nums[i+1] 是不是数组中最小的数,如果是则就删除num[i+1],观察删除该元素后是否是非递减数组,如果nums[i+1]不是最小的,就删除nums[i],再观察删除该元素后是否是非递减数组。沿着上面的思路,碰到一些特定的情况没法通过,例如 [1,3,4,2,5] ,或者[1,2,4,5,3],然后就越改越细,越改越复杂。).
我的代码:
class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
import copy
a = copy.deepcopy(nums)
b = copy.deepcopy(nums)
if len(nums)>2:
for i in range(1,len(nums)-1):
if a[i]>a[i+1]:
del a[i]
del b[i+1]
if (a == sorted(a)) or (b==sorted(b)):
return True
else:
return False
else:
return True
else:
return True
然后对程序稍加修改,速度快了接近4倍:
class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
a,b=nums[:],nums[:]
if len(nums)>2:
for i in range(1,len(nums)-1):
if a[i]>a[i+1]:
del a[i]
del b[i+1]
return ((a == sorted(a)) or (b==sorted(b)))
else:
return True
else:
return True
参考代码:
思路和我的是一样的,只是他是直接替换,我是删除,然后再比较。
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
one, two = nums[:], nums[:]
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
one[i] = nums[i + 1]
two[i + 1] = nums[i]
break
return one == sorted(one) or two == sorted(two)