标签:Given return sequence int number Fibonacci
Source
Find the Nth number in Fibonacci sequence. A Fibonacci sequence is defined as follow: The first two numbers are 0 and 1. The i th number is the sum of i-1 th number and i-2 th number. The first ten numbers in Fibonacci sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ... Example Given 1, return 0 Given 2, return 1 Given 10, return 34 Note The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
题解
斐波那契数列使用递归极其容易实现,其实使用非递归的方法也很容易,不断向前滚动即可。
Java
class Solution { /** * @param n: an integer * @return an integer f(n) */ public int fibonacci(int n) { if (n < 0) return -1; if (n == 1) return 0; if (n == 2) return 1; int fn = 0, fn1 = 1, fn2 = 0; for (int i = 3; i <= n; i++) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return fn; } }
源码分析
- corner cases
- 初始化 fn, fn1, fn2, 建立地推关系。
- 注意 fn, fn2, fn1的递推顺序。
复杂度分析
遍历一次,时间复杂度为 O(n), 使用了两个额外变量,空间复杂度为 O(1).
标签:Given,return,sequence,int,number,Fibonacci 来源: https://www.cnblogs.com/lyc94620/p/14747608.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。