原题链接在这里:https://leetcode.com/problems/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:

  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时看前一个和后一个是否同时为0, 若是就可以栽花. 注意首尾特殊情况.

Time Complexity: O(flowerbed.length).

Space: O(1).

AC Java:

 class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if(flowerbed == null){
throw new IllegalArgumentException("Input array is null.");
} int count = 0;
for(int i = 0; i<flowerbed.length && count<n; i++){
if(flowerbed[i] == 0){
int pre = (i == 0) ? 0 : flowerbed[i-1];
int next = (i == flowerbed.length-1) ? 0 : flowerbed[i+1];
if(pre == 0 && next == 0){
count++;
flowerbed[i] = 1;
}
}
}
return count == n;
}
}

最新文章

  1. C plus plus study note (one)
  2. NPM 如何升级?
  3. Linux下误删除后的恢复操作(ext3/ext4)
  4. 关于DCMTK3.6.1源代码编译的总结
  5. linux上配置jdk+Apache
  6. Runtime 在IOS中的详细使用
  7. 全面理解js面向对象
  8. 解决shell脚本中 echo 怎么写入换行到文件
  9. kvm之六:配置kvm虚拟机通过VNC访问
  10. C# .NET Web API 如何自訂 ModelBinder
  11. java基础(二):谈谈Java基本数据结构
  12. git客户端的安装及使用
  13. A Simple Nim (SG打表找规律)
  14. linux系统服务详解
  15. windows下Qt播放flash
  16. 原生js实现级联下拉列表
  17. Maven整合Spring3.0+Mybatis3.2+Struts2.3+查找坐标+jar包依赖(五)
  18. css学习_css书写规范
  19. Selenium3 + Python3自动化测试系列五——常用断言Assertion
  20. 通过纯代码方式发布WCF服务

热门文章

  1. 17 南宁区域赛 F - The Chosen One 【规律】
  2. PAT 天梯赛 L1-027. 出租 【模拟】
  3. $《第一行代码:Android》读书笔记——第10章 Android网络编程
  4. 建议50:Python中的高级数据结构
  5. google Json
  6. FreeMarker 使用实例
  7. Android 开发人员必须掌握的 10 个开发工具
  8. 彻底弄清python的切片
  9. 语音01_TTS
  10. OpenStack网络新项目Dragonflow研究