605. Can Place Flowers

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;
    }

 

上一篇:Codeforces Round #603 (Div. 2) C. Everyone is a Winner! (数学)


下一篇:K近邻算法04---案例:预测Facebook签到位置