题目:假设你有一个长的多块花坛,其中一些地块种植花,有些不种。条件是花不能种植在相邻的地块 - 他们会争取水,两者都会死亡。
给定一个花坛(表示为包含0和1的数组,其中0表示空白,1表示不为空),给出想要新增n个地块种花,如果n个地块可以种植在其中,而不违反不相邻花规则,则返回ture,否则false。
思路:
假设花坛有是int a = [1,0,0,0,1]则a[2]可以种 1,n为1时返回true,其它false。
考虑这块地的左右是否种了花
代码
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int i = 0, count = 0;
while (i < flowerbed.length) {
if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
count++;
}
if (count>=n){
return true;
}
i++;
}
return false;
}
网友评论