Easy java solution: O(1) space, O(n) time.


  • 0
    G

    We just have to compare its left and right neighbors. If all of its two neighbors are 0, then mark it as a 1.

    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int pre = 0, sum = 0;
        for (int i = 0; i < flowerbed.length - 1; i++) {
          int t = flowerbed[i];
          if (t == 0) {
            int c = (pre == 0 && flowerbed[i + 1] == 0) ? 1 : 0;
            pre = c;
            sum += c;
          } else {
            pre = 1;
          }
        }
        sum += (pre == 0 && flowerbed[flowerbed.length - 1] == 0) ? 1 : 0;
        return sum >= n;
      }
    

Log in to reply
 

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