Leetcode75-605-Can-Place-Flower

🧠 思路总结

总共三种情况:

  1. index = 0时,flowerbed[i + 1] == 0 (or != 0)
  2. index = flowerbed.length - 1时,flowerbed[i - 1] == 0 (or != 0)
  3. 中间的情况:i != 0, i != flowerbed.length - 1
    - flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0 此时可以种

❗ 易错点 / 小坑

  • 边界处理:
    • 数组开头 (i == 0) 或结尾 (i == flowerbed.length-1):开头没有左邻居,结尾没有右邻居,要特别判断。
  • 尽量不要统计连续 0 的数量再计算能放多少花。

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length; i++){
if (flowerbed[i] == 0){
boolean emptyLeft = (i == 0) || (flowerbed[i - 1] == 0);
boolean emptyRight = (i == flowerbed.length - 1) || (flowerbed[i + 1] == 0);
if (emptyLeft && emptyRight){
flowerbed[i] = 1;
count++;
}
}
}
return count >= n;
}
}

Leetcode75-605-Can-Place-Flower
https://powersixxx.github.io/leetcode-blog/2026/01/26/Leetcode75-605-Can-Place-Flower/
作者
Baowen Liu
发布于
2026年1月26日
许可协议