Easy to understand Java solution


  • 0
    Y
    public class Solution {
        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            if(flowerbed == null || flowerbed.length == 0) {
                return n == 0;
            }
            // cover test case of [1] and 1 as input
            if (flowerbed.length == 1 && flowerbed[0] == 1) {
                return n == 0;
            }
            int count = 0;
            int left = 0;
            boolean notComputed = true;
            int i = 1;
            for (; i < flowerbed.length; ++i) {
                if (flowerbed[i] == 0 && flowerbed[i - 1] == 0) {
                    continue;
                } else if (flowerbed[i] != 0) {
                    if (notComputed && left != 0) {
                        count += (i - left - 1) / 2;
                        notComputed = false;
                    } else if (notComputed && left == 0) {
                        count += (i - left) / 2;
                        notComputed = false;
                    }
                } else if (flowerbed[i] == 0) {
                    left = i;
                    notComputed = true;
                }
            }
            if (notComputed) {
                if (left == 0 && i == flowerbed.length) {
                    count += (i - left + 1) / 2;
                } else {
                    count += (i - left) / 2;
                }
            }
            return n <= count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.