605. Can Place Flowers
Input: flowerbed = [1,0,0,0,1], n = 1
Output: TrueInput: flowerbed = [1,0,0,0,1], n = 2
Output: Falseclass Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for(int i = 0; i < flowerbed.length && count < n; 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++;
}
if (count >= n) return true;
}
}
return false;
}
}Last updated