This problem has three kinds of situations:

1. [0,0,1,1,1,] -> 0s start from i=0,  the plant count = zeroNumber/2.

2.[1,0,0,0,1] -> 0s are in between 1, the plant count = zeroNumber-1/2

3.[1,0,1,0,0,0,0] -> 0s end at i=flowerbed.length-1, the plant count = zeroNumber/2.

The solution is as following to deal with the above 3 situations:

    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int zeroCount = 1;  // situation 1
        for (int i = 0; i < flowerbed.length; i++) {
            if (flowerbed[i] == 0) {
                zeroCount++;
            } else {
                n -= (zeroCount - 1) / 2;  //situation 2
                zeroCount = 0;
            }
        }
        n -= (zeroCount) / 2; //situation 3
        return n <= 0;
    }

 

posted on 2022-02-10 09:47  阳光明媚的菲越  阅读(19)  评论(0编辑  收藏  举报