Easy
我自己写得太乱了, 虽然ac了但代码很丑;
参考别人的代码,思路都是Greedy(which I didn't recognize), 但工整很多,比较少重复代码:
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = n;
for(int i = 0; i < flowerbed.length; i++){
if (flowerbed[i] == 0){
int next = (i == flowerbed.length - 1) ? 0 : flowerbed[i + 1];
int prev = (i == 0) ? 0 : flowerbed[i - 1];
if (next == 0 && prev == 0){
flowerbed[i] = 1;
count--;
}
}
}
return count <= 0;
}
}
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = n;
for (int i = 0; i < flowerbed.length; i++){
if (i == 0 && flowerbed.length == 1){
if (flowerbed[0] == 0){
return n <= 1;
} else {
return n == 0;
}
}
if (i == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0){
flowerbed[i] = 1;
count--;
}
if (i > 0 && i < flowerbed.length - 1 && flowerbed[i] == 0 && flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0){
flowerbed[i] = 1;
count--;
}
if (i == flowerbed.length - 1 && flowerbed[i] == 0 && flowerbed[i - 1] == 0){
flowerbed[i] = 1;
count--;
}
}
return count <= 0;
}
}