-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
64 lines (53 loc) · 977 Bytes
/
solution1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* https://leetcode.com/problems/can-place-flowers/
*
* 605. Can Place Flowers
*
* Easy
*
* 60ms 96.15%
* 36.4mb 41.31%
*/
const canPlaceFlowers = (flowerbed, n) => {
const max = flowerbed.length
let ans = 0
let zero = 0
let startIndex = 0
let endIndex = max - 1
// 左边
for (let i = 0; i < max; i++) {
if (flowerbed[i] === 1) {
startIndex = i
break
}
zero++
}
// 全部为空的情况
if (zero === max) {
return Math.floor((zero + 1) / 2) >= n
}
ans += Math.floor(zero / 2)
zero = 0
// 右边
for (let i = max - 1; i >= 0; i--) {
if (flowerbed[i] === 1) {
endIndex = i
break
}
zero++
}
ans += Math.floor(zero / 2)
zero = 0
for (let i = startIndex; i <= endIndex;i++) {
const item = flowerbed[i]
if (item === 0) {
zero++
continue
}
if (zero >= 3) {
ans += Math.floor((zero - 1) / 2)
}
zero = 0
}
return ans >= n
}