当前位置:   article > 正文

Leetcode 605. Can Place Flowers

Leetcode 605. Can Place Flowers

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/502185
推荐阅读
相关标签
  

闽ICP备14008679号