Beats 100% - 14ms.


  • 0
    E

    If the current has placed flower, then we can move the index by 2 to speed up.
    And if all spots are empty are still not satisfy n, then we know the answer is false.

    public class Solution {
        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            
            if(flowerbed.length < (2*n-1)){
                //assume all place has no follower yet, but still not able to plan all n flowers
                return false;
            }
            
            int count = 0;
            int i =0;
            int len = flowerbed.length;
            while(i<len){
                if((i-1<0 || flowerbed[i-1]==0) && (i+1>=len || flowerbed[i+1]==0) && flowerbed[i]==0){
                    count++;
                    i+=2;
                }else if(flowerbed[i]==1){
                    i+=2;
                }else{
                    i++;
                }
            }
            return (count>=n);
        }
    }
    
    

Log in to reply
 

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