力扣链接:605. 种花问题,难度等级:简单。
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 flowerbed
表示花坛,由若干 0
和 1
组成,其中 0
表示没种植花,1
表示种植了花。另有一个数 n
,能否在不打破种植规则的情况下种入 n
朵花?能则返回 true
,不能则返回 false
。
示例 1:
输入: flowerbed = [1,0,0,0,1], n = 1
输出: true
示例 2:
输入: flowerbed = [1,0,0,0,1], n = 2
输出: false
约束:
1 <= flowerbed.length <= 2 * 10^4
flowerbed[i]
为0
或1
flowerbed
中不存在相邻的两朵花0 <= n <= flowerbed.length
思路
检查每个空地块(0
),若其左右均为空(或边界),则可种花(置1
),并计数。若最终计数≥n
,返回true
,否则false
。
步骤
- 初始化计数器
count = 0
。 - 遍历花坛每个地块:
- 若当前为
1
,跳过。 - 若当前为
0
且左右均为0
(或边界),则种花(置1
),count += 1
。
- 若当前为
- 返回
count >= n
。
复杂度
时间复杂度
O(N)
空间复杂度
O(1)
Python #
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
count = 0
for i in range(len(flowerbed)):
if flowerbed[i] == 1:
continue
if (i == 0 or flowerbed[i - 1] == 0) and \
(i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):
flowerbed[i] = 1
count += 1
return count >= n
Java #
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 1) {
continue;
}
if ((i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
count++;
}
}
return count >= n;
}
}
C++ #
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.size(); i++) {
if (flowerbed[i] == 1) {
continue;
}
if ((i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
count++;
}
}
return count >= n;
}
};
JavaScript #
var canPlaceFlowers = function(flowerbed, n) {
let count = 0;
for (let i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] === 1) {
continue;
}
if ((i === 0 || flowerbed[i - 1] === 0) &&
(i === flowerbed.length - 1 || flowerbed[i + 1] === 0)) {
flowerbed[i] = 1;
count++;
}
}
return count >= n;
};
Go #
func canPlaceFlowers(flowerbed []int, n int) bool {
count := 0
for i := 0; i < len(flowerbed); i++ {
if flowerbed[i] == 1 {
continue
}
if (i == 0 || flowerbed[i - 1] == 0) &&
(i == len(flowerbed) - 1 || flowerbed[i + 1] == 0) {
flowerbed[i] = 1
count++
}
}
return count >= n
}
C# #
public class Solution
{
public bool CanPlaceFlowers(int[] flowerbed, int n)
{
int count = 0;
for (int i = 0; i < flowerbed.Length; i++)
{
if (flowerbed[i] == 1)
{
continue;
}
if ((i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.Length - 1 || flowerbed[i + 1] == 0))
{
flowerbed[i] = 1;
count++;
}
}
return count >= n;
}
}
Ruby #
def can_place_flowers(flowerbed, n)
count = 0
flowerbed.each_with_index do |plot, i|
next if plot == 1
if (i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.length - 1 || flowerbed[i + 1] == 0)
flowerbed[i] = 1
count += 1
end
end
count >= n
end