|
4 | 4 | * @return {boolean}
|
5 | 5 | */
|
6 | 6 | var canPlaceFlowers = function (flowerbed, n) {
|
7 |
| - if (n === 0) return true; |
8 |
| - |
9 |
| - let placeNeeded = 1; |
10 |
| - for (let i = 0; i < n; i++) { |
11 |
| - placeNeeded += 2; |
| 7 | + for (let i = 0; i < flowerbed.length; i++) { |
| 8 | + console.log(`i:${i}`) |
| 9 | + if ( |
| 10 | + ((flowerbed[i - 1] ?? 0) === 0) && |
| 11 | + ((flowerbed[i + 1] ?? 0) === 0) && |
| 12 | + (flowerbed[i] === 0) |
| 13 | + ) { |
| 14 | + console.log(`[i - 1]: ${(flowerbed[i - 1])}, [i]: ${(flowerbed[i])}, [i + 1]: ${(flowerbed[i + 1])}`) |
| 15 | + console.log(((flowerbed[i - 1] || 0) === 0)) |
| 16 | + console.log(((flowerbed[i + 1] || 0) === 0)) |
| 17 | + console.log((flowerbed[i] === 0)) |
| 18 | + console.log("what") |
| 19 | + flowerbed[i] = 1; |
| 20 | + n--; |
| 21 | + } |
12 | 22 | }
|
13 | 23 |
|
14 |
| - return (flowerbed.length - 2) >= placeNeeded; |
| 24 | + console.log(`-> n:${n}`) |
| 25 | + |
| 26 | + return n <= 0; |
15 | 27 | };
|
| 28 | + |
| 29 | +let x = |
| 30 | + // canPlaceFlowers([1, 0, 0, 0, 1], 1) // true |
| 31 | + canPlaceFlowers([1, 0, 0, 0, 0, 1], 2) // false |
| 32 | + // canPlaceFlowers([0, 0, 1, 0, 1], 1) // true |
| 33 | + // canPlaceFlowers([1, 0, 0, 0, 1, 0, 0], 2) // true |
| 34 | + // canPlaceFlowers([0, 0, 1, 0, 0], 1) // true |
| 35 | + // canPlaceFlowers([0, 1, 0, 1, 0, 1, 0, 0], 1) // true |
| 36 | + |
| 37 | +console.log("Result") |
| 38 | +console.log(x) |
0 commit comments