605.种花问题

这是一道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),

 

 

相关文章:

  • 2021-07-04
  • 2022-01-29
  • 2022-12-23
  • 2022-12-23
  • 2022-01-15
  • 2021-10-02
  • 2021-12-17
猜你喜欢
  • 2022-01-10
  • 2021-05-17
  • 2021-10-28
  • 2021-10-10
  • 2021-12-21
  • 2022-12-23
  • 2021-07-04
相关资源
相似解决方案