605. Can Place Flowers

https://leetcode.com/problems/can-place-flowers/

solution

# 1. 为减少边界条件判断,前后各增加一块空地。注意循环的边界
# 2. 为剪枝,从n开始倒计时

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        flowerbed = [0] + flowerbed + [0]
        res = 0
        for i in range(1, len(flowerbed) - 1):
            if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
                res += 1
                flowerbed[i] = 1
        return n <= res

时间复杂度:O(n) 空间复杂度:O(1)

Last updated