605.种花问题
题目

提示:
1 <= flowerbed.length <= 2 * 104
flowerbed[i] 为 0 或 1
flowerbed 中不存在相邻的两朵花
0 <= n <= flowerbed.length
解题思路:利用初始条件即不可能有相邻的花,在遇到1时,后一个必定是0,所以可以向后跳两格;遇到0时,因为前一个必定是0,故只需判断下一个是否是0或者是最后一个,如果是0,则count++,如果是1,则该位置不能种花,向后跳3格。
代码实现
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int l=flowerbed.length,count=0;
for(int i=0;i<l;i++){
if(flowerbed[i]==0){
if (i==l-1) {
count++;
}else if (flowerbed[i+1]==0){
count++;
i++;
}
}else {
i++;
}
}
return count>=n?true:false;
}
执行用时


浙公网安备 33010602011771号