You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in?adjacent?plots.
Given an integer array?flowerbed?containing?0's and?1's, where?0?means empty and?1means not empty, and an integer?n, return?if?nnew flowers can be planted in the?flowerbedwithout violating the no-adjacent-flowers rule.
class Solution:
def canPlaceFlowers(self, flowerbed, n):
# pre_zeros 初始值设置为 1,假设最开头是 0,index 0 可种
zeros = 1
count = 0
for each in flowerbed:
# contiguous zeros
if each == 0:
zeros += 1
else:
# 若中间连续 4 个 0 只能种 1 朵,需要 (zeros - 1) // 2
count += (zeros - 1) // 2
zeros = 0
# suf_zeros
count += zeros // 2
return count >= n
?
|