605. Can Place Flowers
Suppose 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 - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
def canPlaceFlowers(flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
index = 0
while n and index < len(flowerbed):
if flowerbed[index] == 0 and (index == 0 or flowerbed[index - 1] == 0) and (
index == len(flowerbed) - 1 or flowerbed[index + 1] == 0):
n -= 1
index += 2
else:
index += 1
return False if n else True
def canPlaceFlowers(flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
count = 1 # [1]
ret = 0
for i in flowerbed:
if not i:
count += 1
else:
if count >= 3:
ret += (count - 1) // 2 # [2]
count = 0
if count >= 2: # [3]
ret += count // 2
return ret >= n