leetcode 561 数组拆分
2020-02-13 本文已影响0人
Arsenal4ever
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