您的位置:首页 > 其它

LintCode-查找斐波纳契数列中第 N 个数

2017-08-10 11:00 309 查看
题目:

查找斐波纳契数列中第 N 个数。

所谓的斐波纳契数列是指:

前2个数是 0 和 1 。

第 i 个数是第 i -1 个数和第 i -2 个数的和。

斐波纳契数列的前10个数字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...


注意事项

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

样例

给定
1
,返回
0


给定
2
,返回
1


给定
10
,返回
34


编码:【推荐方式三】

方式一:编程好理解,但代码复杂,性能较差,且占用内存;LintCode耗时2475ms

public class Solution {
/*
* @param : an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
// write your code here
int[] a = null ;

if(n>2){
a = new int
;
a[0] = 0; a[1] = 1 ;
for(int i=2;i<n;i++){
a[i] = (a[i-1]+a[i-2]);
}
return a[n-1];
}else if(n==1){
return 0;
}else if(n==2){
return 1;
}
return 0;
}
}


方式二:递归,代码量小,但耗时更大,LintCode耗时4526ms

public class Solution {
/*
* @param : an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
// write your code here
if(n==1){
return 0;
}else if(n==2){
return 1 ;
}else if(n>2){
return (fibonacci(n-1) + fibonacci(n-2));
}
return -1;
}
}


方式三:将递归改成for循环,用两个变量来存放前两个数,用c来存放结果;LintCode耗时最短2170ms;

public class Solution {
/*
* @param : an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
// write your code here
if(n==1){
return 0;
}else if(n==2){
return 1 ;
}else{
int a=0;
int b=1;
int c=0;
for(int i=3;i<n+1;i++){
c = a+b;
a=b; //注意先把b赋值给a,在把计算得到的c赋值给b
b=c;
}
return c;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: