605. 种花问题
Suppose you have a long flowerbed in which some of the plots(n. 情节;阴谋;小块土地(plot的复数);平面图) 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.(如果可以在其中种植n朵新花而不违反不相邻花规则,则返回)
1表示有花
0表示没有花
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won’t violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won’t exceed the input array size.
下面3种一次把我拦下来,就根据错误来改
[0,0,1,0,1]
1
预期:
true
[1,0,0,0,1,0,0]
2
预期:
true
[1,0,0,0,0,1]
2
预期:
false
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int x=0;
for(int i=0;i<flowerbed.length;i++){
if(flowerbed.length==1){
if(flowerbed[0]==0)
x++;
break;
}
if(i==0&&flowerbed[i]==0&&i+1<flowerbed.length){
if(flowerbed[1]==1){
flowerbed[0]=-1;
}else{
x++;
flowerbed[0]=1;
}
}else if(i==flowerbed.length-1&&flowerbed[flowerbed.length-1]==0){
if(flowerbed[i-1]==1){
flowerbed[flowerbed.length-1]=-1;
}else{
x++;
flowerbed[i]=1;
}
}else if(flowerbed[i]==0&&(flowerbed[i+1]==1||flowerbed[i-1]==1)){
flowerbed[i]=-1;
}else if(flowerbed[i]==0&&(flowerbed[i-1]==0||flowerbed[i-1]==-1)&&(flowerbed[i+1]==0||flowerbed[i+1]==-1)){
x++;
flowerbed[i]=1;
}
}
return x>=n?true:false;
}
}
我的做法是,
如果只要一个花而且为0直接种下,x++,
否则如果 是花坛的第一个元素,看下第二个位置的元素是不是0
,如果是,在第一个位置种下一朵花,而且x++并且把第一个位置的值设下1(种了花)如果第二个元素是1,
那么不种。并且设值为-1
否则如果是花坛的最后一个位置,看下它前面那个元素是不是1,只要是1,不种,否则(0或者-1)则花坛的最后一个位置种花一朵x++
否则是在花坛的中间位置,如果这个位置没有花(=0)但是前面后面只要有花(=1),那么把这个位置设为-1,不能种花但是是空的位置
否则是在花坛的中间位置,如果这个元素没有花(=0),并且
前面和后面的位置等于0或者等于-1(没有花),就可以种下花一朵x++,把自己的位置设为1,种下花了。
最后循环结束只有符合规则可以种下花的数量>=n则返回true.
然后看了官方题解,我是个sz
二:贪心
public class Solution {
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++;
}
i++;
}
return count >= n;
}
}
我们从左到右扫描数组 flowerbed,如果数组中有一个 0,并且这个 0 的左右两侧都是 0,那么我们就可以在这个位置种花,即将这个位置的 0 修改成 1,并将计数器 count 增加 1。对于数组的第一个和最后一个位置,我们只需要考虑一侧是否为 0。
在扫描结束之后,我们将 count 与 n 进行比较。如果 count >= n,那么返回 True,否则返回 False。
if (flowerbed[i] == 0
&& (i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.length - 1 || flowerbed[i + 1] == 0))
我的天哪,直接很巧妙的把首尾的问题一起放进这个判断了