605. 种花问题
问题描述
https://leetcode.cn/problems/can-place-flowers/description/
解题思路
这题是种左不种右的,我们要求,如果不是边界,则自己本身不是1,而且左右也不能是1.
如果是边界,则自己不是1,且相邻的也不是1.
代码
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: res = 0 for i, v in enumerate(flowerbed): if v == 1: continue flag = True if i-1 >= 0: if flowerbed[i-1] == 0: flag = flag and True else: flag = flag and False if i+1 < len(flowerbed): if flowerbed[i+1] == 0: flag = flag and True else: flag = flag and False if flag: res += 1 flowerbed[i] = 1 return res >= n