题目
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;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int x = arr[i];
int y = arr[j];
int count = 2;
while (set.contains(x + y)) {
int next = x + y;
count++;
x = y;
y = next;
}
result = Math.max(result, count);
}
}
return result > 2 ? result : 0;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)