LeetCode 873. Length of Longest Fibonacci Subsequence(2025/2/27每日一题)

昨天工作耽搁了,没来得及打卡每日一题,今日补上:

标题:Length of Longest Fibonacci Subsequence

题目:

例子:

Example 1:

复制代码
Input: arr = [1,2,3,4,5,6,7,8]
Output: 5
Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].

Example 2:

复制代码
Input: arr = [1,3,7,11,12,14,18]
Output: 3
Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].

解题思路:

  • 先看这道题数量级是10的3次方,因此时间复杂度能接受O(n^2),但不能接受O(n^3)。
  • 确定解题用到的算法及数据结构:要求最长子序列的长度,只要确定子序列最前两个数字,后面的数字都是确定的,因此两层循环确定最前面两个数字,查看整个序列有多少个数字包含在序列中即可。查看的过程可以用unordered_set,查询时间复杂度为O(1)。

代码:

cpp 复制代码
class Solution {
public:
    int lenLongestFibSubseq(vector<int>& arr) {
        unordered_set<int> set(arr.begin(), arr.end());
        int res = 0;
        for(int i = 0; i < arr.size() - 2; i++){
            for(int j = i+1; j < arr.size() - 1; j ++){
                int len = 2, start = arr[i], second = arr[j], next = arr[i] + arr[j];
                while(next <= arr.back() && set.count(next)) {
                    len ++;
                    start = second;
                    second = next;
                    next = start + second;
                }
                if (len > 2) res = max(res, len);
            }
        }
        return res;
    }
};

O(N^2)<时间复杂度<O(N^3)

空间复杂度为O(N)

相关推荐
Wo3Shi4七8 分钟前
哈希冲突
数据结构·算法·go
呆呆的小鳄鱼22 分钟前
cin,cin.get()等异同点[面试题系列]
java·算法·面试
Touper.37 分钟前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun00770039 分钟前
std::forward作用
开发语言·c++·算法
JoernLee1 小时前
机器学习算法:支持向量机SVM
人工智能·算法·机器学习
V我五十买鸡腿1 小时前
顺序栈和链式栈
c语言·数据结构·笔记·算法
我爱一条柴ya1 小时前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
三维重建-光栅投影3 小时前
VS中将cuda项目编译为DLL并调用
算法
课堂剪切板5 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)36 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex