class Solution: def canPlaceFlowers(self, flowerbed, n: int) -> bool: if 1 not in flowerbed: return 2*n-1<=len(flowerbed) res=[] q=0 i=0 j=i+1 c=flowerbed.index(1) if c>1 : q+=c//2 d=flowerbed[::-1].index(1) if d>1 : q+=d//2 flowerbed=flowerbed[c:len(flowerbed)-d] while j<len(flowerbed): if flowerbed[i]==1: i+=1 else: k=i if flowerbed[k]==0 and flowerbed[k]==flowerbed[j]: k,j=j,j+1 else: a=flowerbed[i:j] res.append(a) i=j j+=1 for i in range(len(res)): if len(res[i])>2 and len(res[i])%2==1: q+=len(res[i])//2 elif len(res[i])>2 and len(res[i])%2==0: q+=len(res[i])//2-1 return q>=n
执行用时 :256 ms, 在所有 Python3 提交中击败了43.40%的用户
内存消耗 :14.4 MB, 在所有 Python3 提交中击败了5.13%的用户
两头和中间分别进行计算。
执行用时为 56 ms 的范例 class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if flowerbed.count(1) + n > len(flowerbed)/2 + 1: return False #前后补零法 将两边同样看做中间对待 减少分类情况 nums = [0] + flowerbed + [0] i = 1 count = 0 while i < len(flowerbed)+1: if nums[i-1] == 0 and nums[i] == 0 and nums[i+1] == 0: count += 1 i += 2 else: i += 1 return count >= n
——2019.10.9