File tree Expand file tree Collapse file tree 1 file changed +19
-15
lines changed Expand file tree Collapse file tree 1 file changed +19
-15
lines changed Original file line number Diff line number Diff line change 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} ;
You can’t perform that action at this time.
0 commit comments