LeetCode Can Place Flowers
2024-08-26 17:33:34
原题链接在这里: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:
- 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.
题解:
当前值为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;
}
}
最新文章
- C plus plus study note (one)
- NPM 如何升级?
- Linux下误删除后的恢复操作(ext3/ext4)
- 关于DCMTK3.6.1源代码编译的总结
- linux上配置jdk+Apache
- Runtime 在IOS中的详细使用
- 全面理解js面向对象
- 解决shell脚本中 echo 怎么写入换行到文件
- kvm之六:配置kvm虚拟机通过VNC访问
- C# .NET Web API 如何自訂 ModelBinder
- java基础(二):谈谈Java基本数据结构
- git客户端的安装及使用
- A Simple Nim (SG打表找规律)
- linux系统服务详解
- windows下Qt播放flash
- 原生js实现级联下拉列表
- Maven整合Spring3.0+Mybatis3.2+Struts2.3+查找坐标+jar包依赖(五)
- css学习_css书写规范
- Selenium3 + Python3自动化测试系列五——常用断言Assertion
- 通过纯代码方式发布WCF服务