题目描述:
LeetCode 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 first4
to1
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].
题目大意:
给定包含n个整数的数组,至多改变其中一个数字,判断数组是否可以变为非递减有序
解题思路:
一趟遍历,时间复杂度O(n)
详见代码
Python代码:
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
chance = 1
for x in range(len(nums)):
if x and nums[x] < nums[x - 1]:
if not chance:
return False
chance -= 1
if x > 1 and nums[x] <= nums[x - 2]:
nums[x] = nums[x - 1]
return True
本文链接:http://bookshadow.com/weblog/2017/08/30/leetcode-non-decreasing-array/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。