# leetcode 605. Can Place Flowers（python）

·  阅读 1160

Offer 驾到，掘友接招！我正在参与2022春招打卡活动，点击查看活动详情

### 描述

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 if n new flowers can be planted in the flowerbed 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:

``````1 <= flowerbed.length <= 2 * 10^4
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length

### 解析

• 当 flowerbed.length 为 1 的时候，这块地上没有种植花，这时我们可以种植花
• 当 flowerbed.length 大于 1 的情况下，如果索引为 0 的地块是空地，且右边的是空地，这时我们可以种花
• 如果索引为 N-1 的时候，如果这块地是空地，且左边的也是空地，这时我们可以种花
• 如果索引在中间的位置，如果这块地是空地，且左右两边都是空点，这时我们可以种花

### 解答

``````class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
if n == 0: return True
N = len(flowerbed)
for i, f in enumerate(flowerbed):
if (i == 0 and i + 1 >= N and flowerbed[i] == 0) or \
(i == 0 and i + 1 < N and flowerbed[i + 1] == 0 and flowerbed[i] == 0) or \
(i - 1 >= 0 and i + 1 < N and flowerbed[i + 1] == 0 and flowerbed[i - 1] == 0 and flowerbed[i] == 0) or \
(i == N - 1 and flowerbed[i - 1] == 0 and flowerbed[i] == 0):
n -= 1
flowerbed[i] = 1
if n == 0:
return True
return False

### 运行结果

``````Runtime: 266 ms, faster than 6.88% of Python online submissions for Can Place Flowers.
Memory Usage: 13.7 MB, less than 75.18% of Python online submissions for Can Place Flowers.