这题代码写得很烂
思路:
将flowerbed数组分段,记录区间端点是0是1,保证每个区间端点以外都是连续的0序列,最后对区间端点进行分类讨论
如flowerbed数组为[0,1,0,0,0,0,1]
则分段为:
【0,1】【1,0,0,0,0,1】
对应区间去除端点外所含0序列长度num分别为0和4
当区间端点都为1时,中间0序列所能种的花数最大为(num-1) // 2
当区间端点都为0时,则整个区间除了中间0序列能种花数外,额外能种1朵花
1 class Solution: 2 def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: 3 cnt = left = right = i = 0 4 lens = len(flowerbed) 5 while i < lens: 6 left = flowerbed[i] 7 num,j = 0,i + 1 8 9 while j < lens: 10 right = flowerbed[j] 11 if right == 0: 12 num += 1 13 else:break 14 j += 1 15 16 if left == 1 and right == 1 and num > 1: 17 cnt += (num - 1) // 2 18 elif left == 0 and right == 0: 19 cnt += num // 2 + 1 20 else: 21 num += flowerbed[i] == 0 22 cnt += num // 2 23 i = j 24 return cnt >= n