首页 > 其他 > 详细

【LeetCode】种花问题

时间:2018-05-04 18:06:15      阅读:187      评论:0      收藏:0      [点我收藏+]

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

给定一个花坛(表示为一个数组包含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

 

【LeetCode】种花问题

原文:https://www.cnblogs.com/dreamyu/p/8991571.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!