LintCode-查找斐波纳契数列中第 N 个数
2017-08-10 11:00
309 查看
题目:
查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
前2个数是 0 和 1 。
第 i 个数是第 i -1 个数和第 i -2 个数的和。
斐波纳契数列的前10个数字是:
注意事项
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
样例
给定
给定
给定
编码:【推荐方式三】
方式一:编程好理解,但代码复杂,性能较差,且占用内存;LintCode耗时2475ms
方式二:递归,代码量小,但耗时更大,LintCode耗时4526ms
方式三:将递归改成for循环,用两个变量来存放前两个数,用c来存放结果;LintCode耗时最短2170ms;
查找斐波纳契数列中第 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; } } }
相关文章推荐
- LintCode-二分查找
- LintCode-排序列表转换为二分查找树
- LintCode: 二分查找
- LintCode Find Peak Element(查找峰值)
- Lintcode---单词的添加与查找
- Lintcode(3)-字符串查找
- LintCode Find Peak Element II(查找峰值II)
- lintCode_二分查找
- Lintcode 入门-366斐波纳契数列
- LintCode之13 字符串查找
- lintcode 容易题:Binary Search 二分查找
- Lintcode:字符串查找
- LintCode 13. 字符串查找
- lintcode:二分查找
- lintcode---实现trie--单词的添加与查找
- LintCode 二分查找
- LintCode 13. 字符串查找
- LintCode : 字符串查找
- lintcode-排序列表转换为二分查找树-106
- lintcode- 题106 排序链表转换为二分查找树