今天面试官问了我一个非常经典简单的问题:
给你一个有序递归数组: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)?我想不出来
https://leetcode.cn/problems/fibonacci-number/solutions/545049/fei-bo-na-qi-shu-by-leetcode-solution-o4ze/%7C
可以看下 这篇力扣的通项公式
可能就是问你不用递归的情况下,如何完成吧,因为递归容易“翻车”
【以下回答由 GPT 生成】
有序斐波那契数列查找算法
给你一个有序递归数组:1 1 2 3 5 8,请用java代码告诉我第n位是几(如:第3位是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);
}
}
我又问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);
}
}
下述代码可以实现不浪费空间的斐波那契数列查找算法:
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);
}
}
首先我们可以写一个程序生成好数列,
然后再写一个程序输出数列中需要查找的元素就行了