leetcode 873. Length of Longest Fibonacci Subsequence | 873. 最长的斐波那契子序列的长度

2023-05-16

题目

https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/
在这里插入图片描述

题解

被注释掉的部分是负优化。本意是O(n^2*logM)->O(n^2),然而对set做C(2,992)=491536次insert,比优化掉的logM开销还大。

class Solution {
    public int lenLongestFibSubseq(int[] arr) {
        int n = arr.length;
        HashSet<Integer> set = new HashSet<>();
        for (int a : arr) {
            set.add(a);
        }

        int result = 0;
        // HashSet<String> visited = new HashSet<>(); // "1,2"
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int x = arr[i];
                int y = arr[j];
                // String pair = x + "," + y;
                int count = 2;
                // if (!visited.contains(pair)) {
                    // visited.add(pair);
                    while (set.contains(x + y)) {
                        int next = x + y;
                        count++;
                        x = y;
                        y = next;
                        // visited.add(x + "," + y);
                    }
                // }
                result = Math.max(result, count);
            }
        }
        return result > 2 ? result : 0;
    }
}

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

leetcode 873. Length of Longest Fibonacci Subsequence | 873. 最长的斐波那契子序列的长度 的相关文章

  • 2022-12-19 个人便签1:R&S CMW官方相关手册网址便签

    R amp S CMW官方相关手册网址个人便签 百度了好久CMW的SCPI命令手册 xff0c 然后突然发现官网有给手册网址 xff0c 但是百度没有收录 xff0c 故搬运粘贴到此 关键文档网址 xff1a 主要为Python xff0c
  • IP代理池的获取、维护和池中有效IP的持续使用

    此篇文章可以看作是对知乎分布式爬取中的IP代理设置的扩展 xff0c 记录下IP代理池的获取 维护 和池中有效IP的持续使用 这里还得感谢IP代理池的贡献者 xff0c 我们可以直接在上面下载 xff0c 按照说明配置好环境 xff0c 启

随机推荐