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