LeetCode 665 (Non-decreasing Array)
思路:
声明一个计数器。对比数组中两个相邻的数的大小,如果后者不小于前者,则往下继续比较;如果后者小于前者,则计数器+1,并判断下列两个条件是否满足(不妨设两个数分别为nums[i]和nums[i + 1]):
1. i > 0 且 nums[i + 1] < nums[i - 1]
2. i < len(nums) - 2 且 nums[i + 2] < nums[i]
满足以上任一条件,返回假(因为相隔一个数的两个数之间的大小关系已经无法满足非递减关系,无法调整)。
遍历数组后,如果计数器小于2就返回真,反之则假(因为需要调整的地方过多)。
代码:
class Solution:
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
notIncrease = 0;
for i in range(0, len(nums) - 1):
if nums[i + 1] - nums[i] < 0:
notIncrease += 1
if i and nums[i + 1] < nums[i - 1] and i < len(nums) - 2 and nums[i + 2] < nums[i]:
return False
return notIncrease < 2