zoukankan      html  css  js  c++  java
  • leetcode——873. 最长的斐波那契子序列的长度

    我虽然写出来了,但是超出时间了。。。

     1 class Solution:
     2     def lenLongestFibSubseq(self, A) -> int:
     3         
     4         max1=0
     5         for i in range(len(A)-2):
     6             #对于A中的所有元素,从A[0]开始,m指向A[0],如果A[0]之后的某一个数n与A[0]的和也在A中,则长度为3,
     7             #m指向n,n指向和,进行迭代
     8             m=A[i]
     9             for j in range(i+1,len(A)-1):
    10                 n=A[j]
    11                 length=2
    12                 t=m
    13                 while t+n in A :
    14                     length+=1
    15                     thr=n
    16                     n=t+n
    17                     t=thr
    18                 max1=max(max1,length)
    19         if max1==2:
    20             return 0
    21         else:
    22             return max1

    看了别人的答案,思路和我的一模一样,但是人家就没超出时间,所以就很厉害了。

    如下:

     1 class Solution(object):
     2     def lenLongestFibSubseq(self, A):
     3         S = set(A)
     4         
     5         ans = 0
     6         for i in range(len(A)):
     7             for j in range(i+1, len(A)):
     8                 """
     9                 With the starting pair (A[i], A[j]),
    10                 y represents the future expected value in
    11                 the fibonacci subsequence, and x represents
    12                 the most current value found.
    13                 """
    14                 x, y = A[j], A[i] + A[j]
    15                 length = 2
    16                 while y in S:
    17                     x, y = y, x + y
    18                     length += 1
    19                 ans = max(ans, length)
    20            return ans if ans >= 3 else 0

    人家用了集合set,我没用这个;

    x, y = A[j], A[i] + A[j]
    x, y = y, x + y
    return ans if ans >= 3 else 0

    人家这样的表达都显得更加地道简洁,多学习啊要!!!!

                                                                                          2019.9.26

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    ruby 实现java中的aes 加密解密
    移动端手机端web页面中背景图固定问题
    hooks 组件对应的生命周期
    React 生命周期函数总结
    Sequelize 常用增删改查函数
    如何验证SSH的连通性
    如何生成SSH密钥
    如何查看本机ssh秘钥
    如何更改本地代码仓库指向
    如何发布npm 包
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11592847.html
Copyright © 2011-2022 走看看