
这是一道easy的问题,但是我觉得需要注意的点值得关注:
种花需要两个其两边都是0才能种下,但是开头和结尾有两个0(00- -00)的时候是可以种花的,
有两种方法:一:在开头和结尾加上0,但是这样对空间不友好; 二:单独判断。
下面的做法是不加上0,利用短路或“||”,来对开头和结尾做处理,这样的前提是要把i==0, i==len-1放在或语句的前面判断,这样后面的就会被短路,从而防止越界。
public class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
if(n<1) return true;
int res = 0;
for(int i=0; i<flowerbed.length; i++)
if((flowerbed[i]==0 && (i==0 || flowerbed[i-1]==0) && (i==flowerbed.length-1 || flowerbed[i+1]==0)))
{
flowerbed[i]=1;
res++;
if(res>=n)
return true;
}
return false;
}
}
下面的方法是单独判断:
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int len = flowerbed.length;
int cnt = 0;
for (int i = 0; i < len && cnt < n; i++) {
if (flowerbed[i] == 1) {
continue;
}
int pre = i == 0 ? 0 : flowerbed[i - 1];
int next = i == len - 1 ? 0 : flowerbed[i + 1];
if (pre == 0 && next == 0) {
cnt++;
flowerbed[i] = 1;
}
}
return cnt >= n;
}
时间复杂度都是O(n),

1109

被折叠的 条评论
为什么被折叠?



