[Java] Very easy solution


  • 15
    D
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 1;
        int result = 0;
        for(int i=0; i<flowerbed.length; i++) {
            if(flowerbed[i] == 0) {
                count++;
            }else {
                result += (count-1)/2;
                count = 0;
            }
        }
        if(count != 0) result += count/2;
        return result>=n;
    }

  • 1

    From left to right,
    record the index of last 1, if f[i] is 0, check if this position can be put a 1.
    How can we check? From this example, we can know only the 0 be center of three 0.
    [1,0,0,0,1]

        public boolean canPlaceFlowers(int[] f, int m) {
          int n = f.length;
          int p1 = -2;
          for(int i = 0; i < n; i++){
            if(f[i] == 1) p1 = i;
            else {
              if(i - p1 == 2 && (i + 1 == n || f[i + 1] != 1)){
                m--;
                p1 = i;
              }    
            }
          }
          
          return m <= 0;
        }

  • 0
    S

    @DNfish even I used the same approach. But, instead of using

    result += (count-1)/2;
    

    I am directly using

    n -= (count-1)/2;
    return n < 1;
    

    Not much difference of course :)


  • 0
    K

    I dunt understand ur code


  • 0
    E

    wonderful solution


  • 0
    J

    It is a very good solution, I thought about recursive, but it shows run time error for my O(nlogn)


Log in to reply
 

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