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

 

posted @ 2019-09-26 16:55  欣姐姐  阅读(313)  评论(0编辑  收藏  举报