605. Can Place Flowers

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
// 能种的前提是前后都是 0
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0 && (i - 1 < 0 || flowerbed[i - 1] == 0) && (i + 1 >= flowerbed.length || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
n--;
}
}

return n <= 0;
}
}

References

605. Can Place Flowers