JZ7斐波那契数列
tag:数组
先来一段背景:
斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。n<=39。
示例1
输入
4
返回值
3
解题思路
我用的是最简单的递归思想,直接上代码
代码部分
public class Solution {
public int Fibonacci(int n) {
int result = 1;
int i = 2;
int[] array = new int[n+1];
if(n==0) return 0;
if(n==1) return 1;
if(n>1) {
array[0]=0;
array[1]=1;
}
while(i<=n){
array = getFibonacci(array,i);
i++;
}
result = array[n];
return result;
}
int[] getFibonacci(int[] array,int i){
int temp = 0;
temp = array[i-1]+array[i-2];
array[i]=temp;
return array;
}
}
运行时间:8ms
占用内存:9476k
还没完,让我们来看看大佬写的方法
public class Solution {
public int Fibonacci(int n) {
int f = 0,g = 1;
for(int i=0;i<n;i++){
g += f;
f = g - f;
}
return f;
}
}
简洁美观,tql,向大佬学习
运行时间:7ms
占用内存:9080k
本文介绍了一种计算斐波那契数列指定项的高效方法。通过两种不同的Java实现方式,一种使用数组存储中间结果,另一种采用迭代更新两个变量的方式,实现了对斐波那契数列第n项的有效计算。
198

被折叠的 条评论
为什么被折叠?



