Description

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.

Discuss

只需要计算出一共可以放多少个就可以了。

Code

class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int len = flowerbed.length;
if (len < n) { return false; }
int count = 0;
if (len == 1 && flowerbed[0] == 0) {
count++;
return true;
}
for (int i = 0; i < len; i++) {
if (i == 0) {
if (flowerbed[0] == 0 && flowerbed[1] == 0) {
count++;
flowerbed[0] = 1;
}
continue;
}
if (i == len-1) {
if (flowerbed[i - 1] == 0 && flowerbed[i] == 0) {
count++;
}
break;
}
if (flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
count++;
flowerbed[i] = 1;
}
}
return count >= n;
}
}

最新文章

  1. JS仿淘宝星星评价
  2. iOS十六进制和字符串的相互转换
  3. BZOJ 4717 改装
  4. .net学习笔记---Asp.net的生命周期之二页生命周期
  5. 13、C#基础整理(枚举)
  6. SQL存储过程相关信息查看转
  7. ecshop调用文章显示上一篇下一篇
  8. cocos2d-x 3.0rc2 对于每个包执行情况的重要平台 (超级方便)
  9. maven创建spring项目之后,启动报错java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoade
  10. USACO 1.3.1
  11. codeforces div2 C题思路训练【C题好难,我好菜】
  12. [React] 15 - Redux: practice IM
  13. U盘中病毒,文件消失或不显示
  14. js获取上一个兄弟元素
  15. zTree树
  16. 16个非常酷的jQuery插件
  17. BZOJ3173 TJOI2013最长上升子序列(splay)
  18. javaweb笔记二
  19. POJ 2486 Apple Tree(树形dp)
  20. BZOJ3262:陌上花开 &amp; 洛谷3810:三维偏序——题解

热门文章

  1. Vue项目中引入ElementUI
  2. May 20th 2017 Week 20th Saturday
  3. 【转】OpenGL概述
  4. javascript 面向对象(实现继承的几种方式)
  5. IOS 获取更多的设备信息
  6. PHP设计模式——适配器模式
  7. yarn默认配置
  8. tomcat解决端口号占用问题
  9. ng-repeat 指令(带有数组)
  10. Spring知识点总结(五)Spring整合JDBC