在Python中检查邻接关系会犯错误
我正在处理这个leetcode问题。我得到了一个类似于在Python中检查邻接关系会犯错误,python,algorithm,Python,Algorithm,我正在处理这个leetcode问题。我得到了一个类似于flowerbed=[1,0,0,0,1]的列表和一个类似于n=1的整数。规则是,给定一个包含0和1的整数数组flowerbed,其中0表示空,1表示不空,整数n,如果n可以在花坛中种植新花而不违反无相邻花规则,则返回 示例1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Input: flowerbed = [1,0,0,0,1], n = 2 Output: false 示例2
flowerbed=[1,0,0,0,1]
的列表和一个类似于n=1
的整数。规则是,给定一个包含0
和1
的整数数组flowerbed
,其中0
表示空,1
表示不空,整数n
,如果n
可以在花坛中种植新花而不违反无相邻花规则,则返回
示例1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
示例2:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
这是我的密码。我正在启动一个从索引1到len(flowerbed)-2的for循环,我正在检查当前值、我前面的值和我后面的值是否都是0,如果是,我将把计数器
增加1。最后,通过比较计数器
与n
返回布尔值
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
counter = 0
for i in range(1, len(flowerbed)-2):
if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
counter += 1
return counter == n
然而,对于这个测试用例,它告诉我它没有签出。我不明白为什么。花坛上有两个有效的花点
Input: [1,0,0,0,0,1]
n = 2
Output: true
Expected: false
您还应更新循环中的花坛列表:
if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
counter += 1
flowerbed[i]=1
这样,在尝试种植新种子时,也会考虑放置种子。此外,我将考虑使用<代码>静态方法> /代码>装饰器>代码> CabPoodos.P/>