力扣-10.13-605

在这里插入图片描述
方法一:
我们从左到右扫描数组 flowerbed,如果数组中有一个 0,并且这个 0 的左右两侧都是 0,那么我们就可以在这个位置种花,即将这个位置的 0 修改成 1,并将计数器 count 增加 1。对于数组的第一个和最后一个位置,我们只需要考虑一侧是否为 0。
在扫描结束之后,我们将 count 与 n 进行比较。如果 count >= n,那么返回 True,否则返回 False。

class Solution {
    
    
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    
    
        int i=0,count=0;
		while(i<flowerbed.length) {
    
    
			// 后面两个与情况排列组合只能成立3种情况
			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;
    }
}

猜你喜欢

转载自blog.csdn.net/Desperate_gh/article/details/109047892