【LeetCode】种花问题

假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        """
        :type flowerbed: List[int]
        :type n: int
        :rtype: bool
        """
        count = 0
        can_place = 0
        for index, i in enumerate(flowerbed):
            if index == 0 and i == 0:
                count = 2
                continue
            if index == (len(flowerbed) - 1) and i == 0:
                count += 1
            count = count + 1 if i == 0 else 0
            if count >= 3:
                can_place += 1
                count = 1
        if can_place >= n:
            return True
        elif len(flowerbed) == 1 and i==0:
            return True
        else:
            return False

猜你喜欢

转载自www.cnblogs.com/dreamyu/p/8991571.html
今日推荐