AC O(n) Java Solution. Pretty Straightforward.


  • 0
    K
    public boolean canPlaceFlowers(int[] flowerbed, int numberToPlace) {
            
                    int i=0;
    		
    		if(numberToPlace == 0
    		   || (flowerbed.length == 1 && flowerbed[0] == 0 && numberToPlace == 1)) {			
    			return true;
    		}
    		
    		while(i < flowerbed.length) {
                            // if the current plot is planted, increment by 2.
    			if(flowerbed[i] == 1) {
    				i += 2;
    				continue;
    			}
                            // if the current plot is at 0 index and not planted and the next plot is empty.
    			else if(flowerbed[i] != 1 && i == 0) {
    				if(flowerbed[i+1] != 1) {
    				    flowerbed[i] = 1;
    				    numberToPlace--;
    				}
    				i += 1;
    			}
                            // if the current plot is last index and not planted and the previous plot is empty.
    			else if(flowerbed[i] != 1 && i == flowerbed.length-1) {
    				if(flowerbed[i-1] != 1) {
    				    flowerbed[i] = 1;
    				    numberToPlace--;
    				}
    				i += 1;
    			}
                            // if the current plot is not planted and prev and next plot is empty.
    			else if(flowerbed[i] != 1) {
    				if(flowerbed[i-1] != 1 && flowerbed[i+1] != 1) {
    				    flowerbed[i] = 1;
    				    numberToPlace--;
    				}
    				i += 1;
    			}
    			if(0 == numberToPlace) return true;
    		}		
    		return false;
    	}
    

Log in to reply
 

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