Question:

Share

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

Example:

  1. Input: flowerbed = [1,0,0,0,1], n = 1
  2. Output: True
  1. Input: flowerbed = [1,0,0,0,1], n = 2
  2. Output: False

Solution:

  1. /**
  2. * @param {number[]} flowerbed
  3. * @param {number} n
  4. * @return {boolean}
  5. */
  6. var canPlaceFlowers = function(flowerbed, n) {
  7. //算出可以种植的花朵
  8. let flower = 0 ;
  9. for ( let i = 0; i < flowerbed.length; i++ ) {
  10. if ( flowerbed[i] === 1 ) continue;
  11. if ( i!=0 && flowerbed[i-1]!=0 ) continue;
  12. if ( i!=flowerbed.length-1 && flowerbed[i+1] !=0) continue;
  13. flowerbed[i] = 1;
  14. flower++;
  15. }
  16. return flower >= n ;
  17. };

Runtime: 64 ms, faster than 100.00% of JavaScript online submissions for Can Place Flowers.