1、递归方法 时间复杂度(O(2n))
public static long fibonacci(long index) { if (index == 0) { return 0; } else if (index == 1) { return 1; } else { return fibonacci(index - 1) + fibonacci(index - 2); } }
2、通过对数列中的前两个数相加 时间复杂度(O(n))
public static long fib(long index) { int fib0 = 0; int fib1 = 1; int fib2 = 1; if (index == 0) { return fib0; } else if (index == 1) { return fib1; } else if (index == 2) { return fib2; } else { for (int i = 3; i <= index; i++) { fib0 = fib1; fib1 = fib2; fib2 = fib0 + fib1; } return fib2; } }