我的思路:
当n=0时 直接满足条件
当n>0时 分两种情况:
1.花坛中本来没有花 也就是数组全部都是0
2.花坛中本来有花 这时候要分头尾和中间的情况
①头尾 可以种(0的个数)//2朵花
②中间 可以种(0的个数减去1)//2 朵花
最后比较可以种花的个数和n
我的代码:
def canPlaceFlowers(self, flowerbed, n):
can_plant=0
# 不需要种新的花 直接满足条件
if n==0:
return True
# 需要种花的情况
else:
# 花坛里本来就有花
if 1 in flowerbed:
# 两边都以0开头的情况需要单独讨论
if flowerbed[0]==0:
i=0
while i<len(flowerbed) and flowerbed[i]==0:
i+=1
can_plant+=i//2
flowerbed=flowerbed[i:]
# 将花坛列表转置 重复利用上面的处理列表头的代码
flowerbed=flowerbed[::-1]
if flowerbed[0]==0:
i=0
while i<len(flowerbed) and flowerbed[i]==0:
i+=1
can_plant+=i//2
flowerbed=flowerbed[i:]
# 中间的有普适性的情况
i=0
j=0
while j<len(flowerbed):
# i找到第一个1
while i<len(flowerbed) and flowerbed[i]==0:
i+=1
# j知道到第二个1
j=i+1
while j<len(flowerbed) and flowerbed[j]==0:
j+=1
gap=j-i-1
if gap>2:
can_plant+=(gap-1)//2
i=j
# 花坛里没有花的情况
else:
can_plant=(len(flowerbed)+1)//2
if can_plant>=n:
return True
return False
优秀题解:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if n==0:
return True
m=len(flowerbed)
for i in range(m):
# 判断当前及左右位置是否种植了花
if flowerbed[i]==1:continue
if i>0 and flowerbed[i-1]==1:continue
if i+1<m and flowerbed[i+1]==1:continue
flowerbed[i]=1
n-=1
if n==0:
return True
return False