leetcode和算法----日更

leetcode 665 非递减数列

2020-02-16  本文已影响0人  Arsenal4ever

遍历删除元素,排序看是否相等,超时!!!

class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        for i in range(len(nums)):
            t = nums[:i] + nums[i+1:]
            if sorted(t) == t:
                return True
        return False

找到后一个元素比前一个元素大的数,要么改该元素([4, 5, 5]),要么改该元素后面的元素([4, 5, 4]),就能形成非递减数列。

class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) <= 2:
            return True
        j = 0
        for i in range(len(nums) - 1):
            if nums[i] - nums[i+1] > 0:
                j = i
                break
        l1 = nums[:]
        l2 = nums[:]
        l1[j+1] = l1[j]
        l2[j] = l2[j+1]
        return self.order(l1) or self.order(l2)

    def order(self, nums):
        for i in range(len(nums) - 1):
            if nums[i] - nums[i+1] > 0:
                return False
        return True
上一篇 下一篇

猜你喜欢

热点阅读