今天面试官问了我一个非常经典简单的问题:
给你一个有序递归数组:1 1 2 3 5 8
请用java代码告诉我第n位是几(如:第3位是2)
我用的是正向遍历和反向递归两种方法
但是 面试官问我 能不能不计算
问了chatGpt也是这两种方法:
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 0) {
throw new IllegalArgumentException("输入必须大于0");
}
if (n == 1 || n == 2) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int n = 3;
int result = fibonacci(n);
System.out.println("第" + n + "位是:" + result);
}
}
我又问Gpt能不能不计算fibonacci(n-1)、fibonacci(n-2)这样浪费空间
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 0) {
throw new IllegalArgumentException("输入必须大于0");
}
if (n == 1 || n == 2) {
return 1;
}
int prev = 1;
int current = 1;
for (int i = 3; i <= n; i++) {
int temp = current;
current = prev + current;
prev = temp;
}
return current;
}
public static void main(String[] args) {
int n = 3;
int result = fibonacci(n);
System.out.println("第" + n + "位是:" + result);
}
}
在上述代码中,我们使用了两个变量prev和current,分别代表前一个斐波那契数和当前的斐波那契数。通过循环从3开始迭代,并更新prev和current的值。最后,返回current即表示第n位的斐波那契数。
这种方法的空间复杂度为O(1),只需要常量级的额外空间。
emm.
难道只是用变量替代这么简单吗?
面试官最后问我能不能不计算 (n-1)、(n-2)?我想不出来