题目来源:
leetcode题目,网址:605. 种花问题 - 力扣(LeetCode)
解题思路:
花坛分为完全空的花坛和已经种有花的花坛两种情况,对于前者,直接判断花坛大于等于花坛可种地块数与 2 的商与 n 的大小即可。对于后者,需要对空置地块所在位置分情况讨论。若所种地块左侧或者右侧无花,则可种花数量直接加上空地数整除 2 的结果即可;若所在地块左侧或右侧都有花,则可种花数量需要加上空地数与 1 的差 整除 2 的结果。最后将可种花数量与 n 比较即可。
解题代码:
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int max=0;
int countZero=0;
int i=0;
while(i<flowerbed.length && flowerbed[i]==0 ){ //最左边的空白花坛,只有一边有花
countZero++;
i++;
}
if(i==flowerbed.length){ //花坛中一朵花都没有
countZero= (countZero%2==0? countZero:countZero+1);
max=countZero/2;
return max>=n? true:false;
}
max+=((countZero)/2);
countZero=0;
//位于中间的花坛,两边都有花
while(i<flowerbed.length){
if(flowerbed[i]==0){
countZero++;
}else{
max+=(countZero-1)/2;
countZero=0;
}
i++;
}
max+=(countZero)/2; //最右边的空白花坛,只有一边有花
return max>=n?true:false;
}
}
总结:
注意花坛中可能一朵花都没有即可。