题目描述
给定一个由0和1组成的数组表示花坛,其中0表示没种花,1表示植了花。要再向花坛中种n朵花,要求:相邻花坛不能同时种花。能否在不打破种植规则的情况下种入 n 朵花。
解答
错误解答
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
count = 0
for i in range(0,len(flowerbed)):
if flowerbed[i]==0:
count += 1
if flowerbed[i]==1 and count>2:
count = count - 2
if count==1:
max_num = 1
else:
max_num = round(count/2)
n = n - max_num
if n > 0:
return False
if n<=0:
return True
没有考虑到全为0的情况
错误解答
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
count = 0
for i in range(0,len(flowerbed)):
if flowerbed[i]==0:
count += 1
if flowerbed[i]==1 and count>2:
count = count - 2
if count==1:
max_num = 1
else:
max_num = round(count/2)
n = n - max_num
# 全为0的情况
if count>2:
count = count - 2
if count==1:
max_num = 1
else:
max_num = round(count/2)
n = n - max_num
if n > 0:
return False
else:
return True
遇到1以后没有对count进行更新,如[1,0,1,0,1,0]的情况,循环结束后count为3
错误解答
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
count = 0
block = count
for i in range(0,len(flowerbed)):
if flowerbed[i]==0:
count += 1
if flowerbed[i]==1:
block = count
count = 0
if block>2:
block = block - 2
if block==1:
max_num = 1
else:
max_num = round(block/2)
n = n - max_num
if count==1:
return False
if count>2:
block = count
block = block - 2
if block==1:
max_num = 1
else:
max_num = round(block/2)
n = n - max_num
if n > 0:
return False
if n <= 0:
return True
测试用例[1,0,0,0,0,0,1] 2
我用Spyder运行时输出结果是true,但是力扣上运行输出结果是false,原因未知。
原因找到了:列表内元素类型为int整型,block/2只取整数部分。
没有考虑到一开始就为0的情况,如[0,0,1],1