605. Can Place Flower
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 numbern
, return ifn
new flowers can be planted in it without violating the no-adjacent-flowers rule.
给一个数组, 代表花圃, 和一个数字n
表示要种的画的数量. 问花圃能不能种下这么多的花
花圃有0
和1
组成, 0
表示空位, 1
表示已经有花种在那里了.
如果要往一个空位里面种花, 需要满足一个条件: 该位置左右都是空的.
思路
从左往右扫描, 如果有空位, 判断能否种花, 如果能种, 就种, 不能种继续扫描. 有两个地方西药注意的, 就是数组的第一位和最后一位, 他们只需要判断一边是否为空就可以了.
Code
1 | def canPlaceFlower(flowerbed, n): |
##时间复杂度
$O(n)$
EOF