Java greedy O(n)


  • 0
    K
    public class Solution {
        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            if(n==0) return true;
            int prev = 0, next = 0, len = flowerbed.length;
            for(int i = 0; i < len; ++i) {
                next = (i==(len-1))?0:flowerbed[i+1];
                if(flowerbed[i] == 0 && next == 0 && prev == 0) {
                    if(--n == 0) return true;
                    prev = 1;
                    continue;
                }
                prev = flowerbed[i];
            }
            return false;
        }
    }
    

Log in to reply
 

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