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:

  1. The input array won't violate no-adjacent-flowers rule.
  2. The input array size is in the range of [1, 20000].
  3. n is a non-negative integer which won't exceed the input array size.

思路就是监测, 如果左中右都为0, 那么加1, 并把当前的位置置1, 最后判断ans>=n

Code

class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
fb, ans = [0] + flowerbed + [0], 0
for i in range(1, len(fb) -1):
if fb[i-1] == fb[i] == fb[i+1] == 0:
fb[i] = 1
ans += 1
return ans >= n

最新文章

  1. 在Ubuntu中搭建.NET开发环境
  2. JS设置CSS样式的几种方式
  3. 点击div折叠
  4. Oracle基础 事务
  5. android----sqlite中的 query() 参数分析
  6. DIV隐藏与重显
  7. HTML5 canvas 中的线条样式
  8. IEnumerable实践应用
  9. mvc的filter
  10. hdu_1029_hash/map
  11. JS引擎线程的执行过程的三个阶段(二)
  12. python json模块出现Invalid control character这个异常的原因
  13. Git操作自动触发企业微信机器人webhook
  14. rman实验——测试备份压缩
  15. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(十六)Structured Streaming中ForeachSink的用法
  16. OpenNebula学习第三节之虚拟机管理
  17. Android开发的16条小经验总结
  18. 使用JPush(极光推送)实现远程通知
  19. 小白第一次使用Git随笔
  20. iOS 使用AFNetworking 设置cookie

热门文章

  1. R语言(入门小练习篇)
  2. 游戏服务器学习笔记 3———— firefly 的代码结构,逻辑
  3. python框架---->pymysql的使用
  4. jstorm开发指南-写个简单的jstorm应用
  5. Win7/Win8/IIS7/IIS8配置ASP/ACCESS
  6. maven中properties标签定义变量
  7. 使用 intellijIDEA + gradle构建的项目如何debug
  8. IOS开发 REST请求 ASIHTTPRequest用法
  9. python pytest测试框架介绍一
  10. Shell for