Leetcode学习笔记:#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.
实现:
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++;
}
}
}
return count == n;
}
思路:
每遍历一个位置便判断其前后是否为0,如果不为则可以设置其为1,且count+1,最后返回count是否等于n。