LeetCode Solutions
605. Can Place Flowers
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
if (n == 0)
return true;
for (int i = 0; i < flowerbed.size(); ++i)
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
if (--n == 0)
return true;
}
return false;
}
};
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if (n == 0)
return true;
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;
if (--n == 0)
return true;
}
return false;
}
}
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
for i, flower in enumerate(flowerbed):
if flower == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):
flowerbed[i] = 1
n -= 1
if n <= 0:
return True
return False