Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

实现findFibonacci函数,在一堆正整数中,找到最长的一组斐波那契数列段

javascript 编程题

// 实现findFibonacci函数,在一堆正整数中,找到最长的一组斐波那契数列段
// 斐波那契数列:一个递增的正整数数列,从第三位起,每个数字都是前两位数字之和,不一定要从 1 开始
// 入参格式参考:
const inputArr = [13, 9, 3, 8, 5, 25, 31, 11, 21];

// 出参格式参考:
//const sequence = [3, 5, 8, 13, 21];

网上大部分的方法,都是找到最长的number,没有返回完整的lists;
完整lists的函数要怎么写吗

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

一个直观解答,应该不是最优,时间复杂度太高了,超过了O(n ^ 2)。
返回值未处理长度不足3的情况:

function findFibnacci(list) {
    const map = {}, results = []
    for (let num1 of list) {
        map[num1] = true
        for (let num2 of list) {
            if (num2 > num1) {
                results.push([num1, num2])
            }
        }
    }
    let longest = []
    while (results.length) {
        for (let i = results.length - 1; i >= 0; i--) {
            let result = results[i]
            let n1 = result[result.length - 2]
            let n2 = result[result.length - 1]
            let next = n1 + n2
            if (!map[next]) {
                if (result.length > longest.length) {
                    longest = result
                }
                results.splice(i, 1)
                continue
            }
            result.push(next)
        }
    }
    return longest
}

let res = findFibnacci([13, 9, 3, 8, 5, 25, 31, 11, 21])
console.log(res)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...