LeetCode 605. 种花问题

题目链接

605. 种花问题

题目分析

思路比较简单,直接写代码注释里了。

代码实现

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int res = 0;
        //假想在数组中左右边界添加0,便于处理。
        int count = 1;
        for(int i = 0; i < flowerbed.length; i++){
            if(flowerbed[i] == 0){
                count++;
            }else{
                count = 0;
            }
            //如果遇到3个连续0的情况,就可以种一支花。同时当前这个0又可以充当下一个种花的起始0,所以就直接count = 1
            if(count == 3){
                res++;
                count = 1;
            }
        }
        //如果末尾仍然存在两个0,因为我们假想在边界添加0,所以事实上会有3个0,这时候还可以再插一枝花。
        if(count == 2){
            res++;
        }
        return n <= res;
    }
}
原文地址:https://www.cnblogs.com/ZJPaang/p/13693040.html