Java--种花的问题
来源:互联网 发布:笔记本usb端口上的电涌 编辑:程序博客网 时间:2024/04/30 11:38
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 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 = 1Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2Output: False
Note:
- The input array won't violate no-adjacent-flowers rule.
- The input array size is in the range of [1, 20000].
- n is a non-negative integer which won't exceed the input array size.
public class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { }}
解决方法:
public class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int count = 0; for(int i = 0; i < flowerbed.length && count < n; i++) { if(flowerbed[i] == 0) { //get next and prev flower bed slot values. If i lies at the ends the next and prev are considered as 0. int next = (i == flowerbed.length - 1) ? 0 : flowerbed[i + 1]; int prev = (i == 0) ? 0 : flowerbed[i - 1]; if(next == 0 && prev == 0) { flowerbed[i] = 1; count++; } } } return count == n; }}
阅读全文
0 0
- Java--种花的问题
- 种花的邮差
- 种花的邮差
- 种花
- ACM二哥种花生问题
- 120种花的花语~
- 世界上最罕见的7种花
- 适合电脑族的3种花茶
- 刚认的两种花[蟹爪兰、水仙]
- 喵哈哈村的种花魔法
- AOJ894 种花【图的搜索+回溯】
- 内存泄露的八种花样
- 职场新人不能做的5种花
- 种花家生日快乐! hdu 1251 简单的字典树
- smoj2084:种花(无汇源的可行流)
- JZOJ4726. 种花
- Jzoj4726 种花
- 园丁的乐趣 惬意的游戏,种花游戏 【安卓软件】
- C# 匿名方法
- Android Studio的图片到底是放在drawable还是mipmap呢
- Spring Boot学习(简介-Hello World)
- Kotlin 语言基本语法的使用
- GeoHash经度估算
- Java--种花的问题
- 浅析jQuery的基础设计模式
- 二叉树和二叉查找树
- C语言可以干些什么?C语言主要涉及哪些IT领域?
- Sublime Text Build 3126 x64 安装
- zkw线段树
- 说说 JavaScript 事件流之事件类型(包含 DOM2、DOM3 级事件)
- C# Lambda表达式
- Java多态的理解