美文网首页
leetcode 561 数组拆分

leetcode 561 数组拆分

作者: Arsenal4ever | 来源:发表于2020-02-13 22:11 被阅读0次

    561 这道题花里胡哨的,直接排序,取下标为奇数的加一起求和就行了。

    class Solution(object):
        def arrayPairSum(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            nums.sort()
            return sum(nums[i] for i in range(0, len(nums), 2))
    

    605 这道题只要前面数、当前数和后面数都为0,就把当前数设置为1,遍历过去!!!最伟大的地方在于在起始和终止都添加一个0,看评论说这叫防御式编程思想!!!

    class Solution(object):
        def canPlaceFlowers(self, flowerbed, n):
            """
            :type flowerbed: List[int]
            :type n: int
            :rtype: bool
            """
            flowerbed.append(0)
            flowerbed.insert(0, 0)
            flowers = 0
            for i in range(1, len(flowerbed)-1):
                if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
                    flowerbed[i] = 1
                    flowers += 1
            return n <= flowers 
    

    相关文章

      网友评论

          本文标题:leetcode 561 数组拆分

          本文链接:https://www.haomeiwen.com/subject/mifrfhtx.html