Leetcode 605. Can Place Flowers

295 篇文章 2 订阅
150 篇文章 0 订阅
文章介绍了如何在满足不相邻花坛规则的情况下,给一个包含空地和已种植区域的花坛种n朵新花。通过遍历花坛,每次将花种在左侧或右侧空地,直到无法再种或花的数量达到限制。给出一个Solution类的方法实现这一过程并返回布尔值结果。
摘要由CSDN通过智能技术生成

Problem

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0’s and 1’s, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

Algorithm

Greedy. Place the flower in the leftmost available position each time, maximizing the number of flowers that can be placed.

Code

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        bed_size = len(flowerbed)
        for i in range(bed_size):
            if (i == 0 or not flowerbed[i-1]) and (i == bed_size-1 or not flowerbed[i+1]) and not flowerbed[i]:
                flowerbed[i] = 1
                n -= 1
                if n <= 0:
                    return True
        return n <= 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值