665. Non-decreasing Array

这题难度为简单,目前通过率为20.3%

题目:

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].

题目大意是给出一个有n个数的列表,能否指通过修改一个数字就能使这个列表变成一个递增数列。

思路:
用一个bool变量用来判断是否修改过数字。修改数字的方法大概有以下几种:
1.题目给的[4,2,3],因为需要修改的数字是第一个数,因此直接把第一个数改成和第二个数相同即可
2.[2,4,3],除了第一个数之外,为了方便可以直接把要修改的数改成前一个数,例如改成[2,2,3]。
3.[1,4,2,3],此时如果把2修改成4,则又需要把3改成4使得返回Flase。但最优办法是把4改成1或者2。因此方法修改成和前两个数相比较,如果是[1,4,2]这种中间大两头小,则修改中间的数,否则修改最后一个数。

代码:

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

复杂度分析:

由于只有一个for循环,因此时间复杂度T(n)=O(n)。

提交:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_36475045/article/details/80068741