Java Solution 11ms beats 100%


  • 0
    V

    public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int count=0;
    for(int i=0;i<flowerbed.length;i++) {
    if(flowerbed.length==1){
    if(flowerbed[i]==0) count++;
    }
    else if(i==flowerbed.length-1 && flowerbed[i]==0 && flowerbed[i-1]==0) count++;
    else if(flowerbed[i]==1) i++;
    else {
    if(flowerbed[i+1]==0)
    {
    count++;
    i++;
    }
    }
    }
    return count>=n ? true:false;
    }
    We try to only forward check by skipping when we get a 1 or can place a new 1 at a position. For example 1,0,0,0,1 we skip checking the second positon because the first position is a 1, simlarly for the third position. Its efficient but not the cleanest code.


Log in to reply
 

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