Skip to content

Commit 410851c

Browse files
committed
add 第9题斐波那契数列
1 parent 8ff7241 commit 410851c

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.leosanqing.algorithm;
2+
3+
/**
4+
* @Author: leosanqing
5+
* @Date: 2019-11-16 18:42
6+
*
7+
* 面试题 10 斐波那契数列
8+
* 现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
9+
*/
10+
public class _10_Fibonacci {
11+
public static void main(String[] args) {
12+
13+
// System.out.println(method1(50);
14+
System.out.println(method1(40) == method2(40));
15+
}
16+
17+
18+
/**
19+
* 采用递归的思想,这种最常见但是效率极低。
20+
* 并且会有栈溢出的情况
21+
*
22+
* @param n
23+
* @return
24+
*/
25+
private static long method1(int n) {
26+
if (n <= 0) {
27+
return 0;
28+
}
29+
if (n == 1) {
30+
return 1;
31+
}
32+
return method1(n - 1) + method1(n - 2);
33+
}
34+
35+
36+
/**
37+
* 我们只需要知道两个数,要计算当前的就只要知道他前面的两个数。
38+
* 我们只要每次计算这两个就行。
39+
*
40+
* 这样时间复杂度就是 O(n)
41+
* @param n
42+
* @return
43+
*/
44+
private static long method2(int n) {
45+
int[] nums = {0, 1};
46+
47+
if (n < 2) {
48+
return nums[n];
49+
}
50+
// 前面的数 n-2
51+
long one = 1;
52+
// 第二个数 n-1
53+
long two = 0;
54+
// 当前数
55+
long fibN = 0;
56+
for (int i = 2; i <= n; i++) {
57+
fibN = one + two;
58+
two = one;
59+
one = fibN;
60+
}
61+
return fibN;
62+
}
63+
64+
}

0 commit comments

Comments
 (0)