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

题目:

查找斐波纳契数列中第 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

 1 public class Solution {
 2     /*
 3      * @param : an integer
 4      * @return: an ineger f(n)
 5      */
 6     public int fibonacci(int n) {
 7         // write your code here
 8         int[] a = null ;
 9         
10         if(n>2){
11             a = new int[n];
12             a[0] = 0; a[1] = 1 ;
13             for(int i=2;i<n;i++){
14                 a[i] = (a[i-1]+a[i-2]);
15             }
16             return a[n-1];
17         }else if(n==1){
18             return 0;
19         }else if(n==2){
20             return 1;
21         }
22         return 0;
23     }
24 }

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

 1 public class Solution {
 2     /*
 3      * @param : an integer
 4      * @return: an ineger f(n)
 5      */
 6     public int fibonacci(int n) {
 7         // write your code here
 8        if(n==1){
 9            return 0;
10        }else if(n==2){
11            return 1 ;
12        }else if(n>2){
13            return (fibonacci(n-1) + fibonacci(n-2));
14        }
15        return -1;
16     }
17 }

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

 1 public class Solution {
 2     /*
 3      * @param : an integer
 4      * @return: an ineger f(n)
 5      */
 6     public int fibonacci(int n) {
 7         // write your code here
 8        if(n==1){
 9            return 0;
10        }else if(n==2){
11            return 1 ;
12        }else{
13             int a=0;
14             int b=1;
15             int c=0;
16             for(int i=3;i<n+1;i++){
17                 c = a+b;
18                 a=b; //注意先把b赋值给a,在把计算得到的c赋值给b
19                 b=c;
20             }
21             return c;
22        }
23     }
24 }
原文地址:https://www.cnblogs.com/crazytrip/p/7338102.html