leetcode 873. Length of Longest Fibonacci Subsequence | 873. 最长的斐波那契子序列的长度

x33g5p2x  于2022-07-07 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(303)

题目

https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/

题解

被注释掉的部分是负优化。本意是O(n^2*logM)->O(n^2),然而对set做C(2,992)=491536次insert,比优化掉的logM开销还大。

  1. class Solution {
  2. public int lenLongestFibSubseq(int[] arr) {
  3. int n = arr.length;
  4. HashSet<Integer> set = new HashSet<>();
  5. for (int a : arr) {
  6. set.add(a);
  7. }
  8. int result = 0;
  9. // HashSet<String> visited = new HashSet<>(); // "1,2"
  10. for (int i = 0; i < n; i++) {
  11. for (int j = i + 1; j < n; j++) {
  12. int x = arr[i];
  13. int y = arr[j];
  14. // String pair = x + "," + y;
  15. int count = 2;
  16. // if (!visited.contains(pair)) {
  17. // visited.add(pair);
  18. while (set.contains(x + y)) {
  19. int next = x + y;
  20. count++;
  21. x = y;
  22. y = next;
  23. // visited.add(x + "," + y);
  24. }
  25. // }
  26. result = Math.max(result, count);
  27. }
  28. }
  29. return result > 2 ? result : 0;
  30. }
  31. }

相关文章