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
containing0
's and1
's, where0
means empty and1
means not empty, and an integern
, return ifn
new flowers can be planted in theflowerbed
without 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