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)

相关推荐
CoovallyAIHub2 小时前
Moonshine:比 Whisper 快 100 倍的端侧语音识别神器,Star 6.6K!
深度学习·算法·计算机视觉
CoovallyAIHub3 小时前
速度暴涨10倍、成本暴降6倍!Mercury 2用扩散取代自回归,重新定义LLM推理速度
深度学习·算法·计算机视觉
CoovallyAIHub3 小时前
实时视觉AI智能体框架来了!Vision Agents 狂揽7K Star,延迟低至30ms,YOLO+Gemini实时联动!
算法·架构·github
CoovallyAIHub4 小时前
开源:YOLO最强对手?D-FINE目标检测与实例分割框架深度解析
人工智能·算法·github
CoovallyAIHub4 小时前
OpenClaw:从“19万星标”到“行业封杀”,这只“赛博龙虾”究竟触动了谁的神经?
算法·架构·github
刀法如飞4 小时前
程序员必须知道的核心算法思想
算法·编程开发·算法思想
徐小夕5 小时前
pxcharts Ultra V2.3更新:多维表一键导出 PDF,渲染兼容性拉满!
vue.js·算法·github
CoovallyAIHub6 小时前
OpenClaw一脚踩碎传统CV?机器终于不再只是看世界
深度学习·算法·计算机视觉
CoovallyAIHub7 小时前
仅凭单目相机实现3D锥桶定位?UNet-RKNet破解自动驾驶锥桶检测难题
深度学习·算法·计算机视觉
zone77397 小时前
002:RAG 入门-LangChain 读取文本
后端·算法·面试