提供另外一种思路

来源:3-7 种花问题-代码演示

木南1988

2019-02-20

export default (arr, n) => {

let count = 0;
for (let i = 0; i < arr.length; i++) {
let pre = arr[i-1]
let next = arr[i+1]
const curr = arr[i]
if (pre === undefined) pre = 0
if (next === undefined) next = 0
if (pre === 0 && curr === 0 && next === 0) {
arr.splice(i, 1, 1)
count++
}
}
return count >= n
}

写回答

4回答

学无止境DDH

2019-03-01

const canPlaceFlowers = (flowerbed, n) => {
    let count = 0
    let left = 0
    let current, right

    for (let i = 0; i < flowerbed.length;) {
        current = flowerbed[i]
        right = flowerbed[i + 1] ? flowerbed[i + 1] : 0
        if (left) {
            i++
            left = current
            continue
        }
        if (!current && !right) {
            count += 1
            i += 2
            left = right
        } else {
            i += 2
            left = right
        }
    }

    return count >= n
}

思路都差不多。。。

0
0

吐司吐司

2019-02-24

学习了

0
0

吐司吐司

2019-02-24

咱俩思路差不多..但是 我比较啰嗦 写的太麻烦了 学习了兄弟..

0
0

快乐动起来呀

2019-02-20

欢迎贡献到issue,感谢

0
0

JavaScript版 数据结构与算法

填补前端同学的算法短板,掌握面试中最常见的算法与数据结构

2467 学习 · 395 问题

查看课程