- 题目:
假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花? 能则返回True,不能则返回False。
示例 1:
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True
示例 2:
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False
注意:
数组内已种好的花不会违反种植规则。
输入的数组长度范围为 [1, 20000]。
n 是非负整数,且不会超过输入数组的大小。
- 实现:
public static void main(String[] args) {
int n = 5; //代表要种的花朵数
//花台现状
int[] flowerbed = new int[] {1,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0};
int len = flowerbed.length;
for (int i : flowerbed) {
//打印种花前的花台
System.out.print("\t"+i);
}
System.out.println();
for(int i=0; i<len&&n>0; i++){
if(flowerbed[i] != 0) {
//跳过已经种过花的位置
continue;
}
//当前位置的左右位置下标
int left = i-1;
int right = i+1;
//左右位置是否已种花(默认都未种)
int leftVal = 0, rightVal = 0;
if(left >= 0){
leftVal = flowerbed[left];
}
if(right < len){
rightVal = flowerbed[right];
}
if(leftVal==0 && rightVal==0){
//左右都未种花,则当前位置可种花
flowerbed[i] = 2; //设置为2是为了便于观察种花的位置,也可设置为1
n--; //剩余花的数量-1
i++; //跳过下一个位置,因为当前位置种了花,下一个位置一定不能种花
}
}
for (int i : flowerbed) {
//打印种花后的花台
System.out.print("\t"+i);
}
System.out.println();
System.out.println("是否可以种完:"+(n==0)); //n=0证明种n朵花可行
}
- 打印结果:
1 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0
1 0 2 0 1 0 0 1 0 2 0 2 0 0 1 0 2 0 2
是否可以种完:true