您的位置:首页 > 职场人生

剑指offer 面试题9 斐波那契数列 java版答案

2016-11-15 17:25 597 查看
package OfferAnswer;
/**
* 面试题09
* 斐波那契数列
* @author lwk
*
*/
public class Answer09 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(Fibonacci1(40));
long end = System.currentTimeMillis();
System.out.println(end - start);
}
//递归解法 时间复杂度指数递增
public static long Fibonacci1(int n){
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
return Fibonacci1(n-1) + Fibonacci1(n-2);
}

//时间复杂度O(n)的解法
public static long Fibonacci2(int n){
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
long first = 0;
long second = 1;
long result = 0;
for (int i = 2; i <= n; i++) {
result = first + second;
first = second;
second = result;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: