LeetCode605-中花问题

题目链接

英文链接:https://leetcode.com/problems/can-place-flowers/

中文链接:https://leetcode-cn.com/problems/can-place-flowers/

题目详述

假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。

示例 1:

1
2
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True

示例 2:

1
2
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False

注意:

  1. 数组内已种好的花不会违反种植规则。
  2. 输入的数组长度范围为 [1, 20000]。
  3. n 是非负整数,且不会超过输入数组的大小。

题目详解

贪心算法。按题目要求模拟即可,满足条件的位置必然前中后三个位置都为 0(前、后如果存在的话)。

方法一:直接比较统计。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class LeetCode_00605 {

public boolean canPlaceFlowers(int[] flowerbed, int n) {
int len = flowerbed.length;
if (len < 2 * n - 1) {
return false;
}
for (int i = 0; i < len && n > 0; ) {
int next = i + 1 < len ? flowerbed[i + 1] : 0;
if (flowerbed[i] == 0 && next == 0) {
--n;
i += 2;
} else {
while (++i < len && flowerbed[i] == 1) {}
++i;
}
}
return n == 0;
}
}

方法二:数连续的 0 的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LeetCode_00605 {

public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 1;
int res = 0;
for (int i = 0; i < flowerbed.length; ++i) {
if (flowerbed[i] == 0) {
++count;
} else {
res += (count - 1) / 2;
count = 0;
}
}
if (count != 0) {
res += count / 2;
}
return res >= n;
}
}