605. 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为奇数,连续0为偶数,如果连续0在最左边,在最右边,在中间,分情况讨论,最终比较sum和n的大小。
public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if (flowerbed == null || flowerbed.length == 0) {
return false;
}
if (n == 0) {
return true;
}
int count = 0;
int sum = 0;
// [0], 1的情况
if (flowerbed.length == 1) {
if (flowerbed[0] == 0) {
sum = 1;
}
}
for (int i = 0; i < flowerbed.length; i++) {
count = 0;
while (i < flowerbed.length - 1 && flowerbed[i] == 0) {
count++;
i++;
}
// i最多加到flowerbed.length - 1,但是flowerbed.length - 1对应位置的值没有计算。
if (i + 1 == flowerbed.length && flowerbed[i] == 0) {
count++;
}
if (count > 0) {
if (count % 2 == 0) {
// 最左边或者最右边
if (count == i || flowerbed.length == i + 1 && flowerbed[i] == 0) {
sum += count / 2;
// 中间
} else {
sum += count / 2 - 1;
}
} else {
// 全部为0
if (count == i + 1 && count == flowerbed.length) {
sum += count / 2 + 1;
} else {
sum += count / 2;
}
}
}
}
return sum >= n;
}
}
解法二
当前元素为0,并且前后都为0,该位变为1,count加1.
public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if (flowerbed == null || flowerbed.length == 0) {
return false;
}
if (n == 0) {
return true;
}
int count = 0;
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0)
&& (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
count++;
}
if (count >= n) {
return true;
}
}
return false;
}
}