hw7 (Week 8)

LeetCode 665 (Non-decreasing Array)

Idea:
declare a counter. Compare the sizes of two adjacent numbers in the array, if the latter is not less than the former, continue to compare; if the latter is less than the former, the counter +1, and judge whether the following two conditions are satisfied (maybe set two numbers nums[i] and nums[i + 1] respectively):
1. i > 0 and nums[i + 1] < nums[i - 1]
2. i < len(nums) - 2 and nums[i + 2 ] < nums[i]
satisfies any of the above conditions, and returns false (because the size relationship between two numbers separated by a number can no longer satisfy the non-decreasing relationship and cannot be adjusted).
After traversing the array, return true if the counter is less than 2, and false otherwise (because there are too many places to adjust).
Code:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735227&siteId=291194637