赞
踩
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.
Greedy. Place the flower in the leftmost available position each time, maximizing the number of flowers that can be placed.
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。