Skip to content

Commit aa9fe6d

Browse files
author
aestheticw3
authored
Update 0605-can-place-flowers.js
1 parent b1c121f commit aa9fe6d

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

javascript/0605-can-place-flowers.js

+19-15
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
1-
// time complexity is O(n).
1+
/**
2+
* Loop Solution
3+
* Time O(N) | Space O(1)
4+
* https://leetcode.com/problems/can-place-flowers
5+
* @param {number[]} fb
6+
* @param {number} n
7+
* @return {boolean}
8+
*/
29

3-
var canPlaceFlowers = function(flowerbed, n) {
4-
5-
for(let i = 0; i < flowerbed.length; i++) {
6-
if(flowerbed[i] === 0) {
7-
if((flowerbed[i-1] === 0 && flowerbed[i+1] === 0) ||
8-
(flowerbed[i-1] === undefined && flowerbed[i+1] === 0) ||
9-
(flowerbed[i+1] === undefined && flowerbed[i-1] === 0) ||
10-
(flowerbed[i-1] === undefined && flowerbed[i+1] === undefined && flowerbed[i] === 0)) {
10+
var canPlaceFlowers = function (fb, n) {
11+
if (n === 0) return true;
1112

12-
flowerbed[i] = 1;
13-
n--;
14-
}
15-
}
16-
}
13+
for (let i = 0; i < fb.length; i++) {
14+
if (fb[i] === 0) {
15+
fb[i - 1] !== 1 && fb[i + 1] !== 1 && n-- && i++;
16+
} else {
17+
i++;
18+
}
19+
if (n === 0) return true;
20+
}
1721

18-
return n > 0 ? false : true;
22+
return false;
1923
};

0 commit comments

Comments
 (0)