Java solution


  • 0
    Z

    public class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {

        if( flowerbed.length == 1){
            if( flowerbed[0] == 1){
                return n==0?true:false;
            }
            else {
                return true;
            }
        }
        
        
        for(int i= 0; i<flowerbed.length; i++){
            
            if( i == 0){
                if( flowerbed[i+1] == 0 && flowerbed[i] == 0){
                    n--;
                    flowerbed[i] = 1;
                }
            }
            else if( i == flowerbed.length-1){
                
                if(flowerbed[i-1] == 0 && flowerbed[i] == 0 ){
                    n--;
                    flowerbed[i] = 1;
                }
    
            }
            else{
                if( flowerbed[i-1] == 0 && flowerbed[i+1] == 0 && flowerbed[i] == 0){
                
                n--;
                
                flowerbed[i] = 1;
                }
            }
        }
        return n <= 0;
    }
    

    }


Log in to reply
 

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