- 题目描述
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组 flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false
- 示例
输入:flowerbed = [1,0,0,0,1], n = 1
输出:true
输入:flowerbed = [1,0,0,0,1], n = 2
输出:false
- 提示
1 <= flowerbed.length <= 2 * 104
flowerbed[i] 为 0 或 1
flowerbed 中不存在相邻的两朵花
0 <= n <= flowerbed.length
- 分析 – 贪心算法
贪心策略:不打破种植规则的情况下多种植花
在两个相邻花地间的空地尽可能的多种植花
记录下相邻两块花地的坐标pre
,cur
,根据cur
-pre
判断能够种花
考虑边界条件 数组下标0
flowerbed.length - 1
没有种花的情况
- Code
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0; // 记录空地可种花数
int pre = -1; // 记录两块花地的第一块花地位置
for (int cur=0; cur<flowerbed.length; cur++) {
if (flowerbed[cur] == 1) {
if (pre == -1) {
count += cur / 2;
} else {
count += (cur - pre - 2) / 2;
}
if (count >= n) return true;
pre = cur;
}
}
if (pre == -1) { // 全为空地
count += (flowerbed.length + 1) / 2;
} else {
count += (flowerbed.length - pre - 1) / 2;
}
return count >= n;
}
}
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int cnt = 0; // 记录相邻两块花地能种的数花
boolean flag = false; // 标识开始并没有种花
for (int i=0; i<flowerbed.length; i++) {
if (flowerbed[i] == 1) {
if (flag) {
n -= (cnt - 1) / 2;
} else { // 第一块地没有种花
n -= cnt / 2;
}
flag = true;
cnt = 0;
} else {
++cnt;
if (i == flowerbed.length - 1) { // 最后一块地没有种花
if (!flag) { // 自始至终没有种花
n -= (cnt + 1) / 2;
} else {
n -= cnt / 2;
}
}
}
}
return n <= 0;
}
}
- 复杂度
时间复杂度:O(n),其中n是数组flowerbed 的长度。需要遍历数组一次。
空间复杂度:O(1),额外使用的空间为常数。