首页 > 代码库 > [Twitter] Fibonacci Sequence
[Twitter] Fibonacci Sequence
Question:
Given a number n, give me a function that returns the nth fibonacci number. Running time, space complexity, iterative vs. recursive.
http://www.glassdoor.com/Interview/Given-a-number-n-give-me-a-function-that-returns-the-nth-fibonacci-number-Running-time-space-complexity-iterative-vs-r-QTN_250204.htm
// Recusive // O(2^n) public int fibonacci(int n) { if (n <= 0) return 0; if (n == 1) return 1; if (n == 2) return 2; return fibonacci(n - 2) + fibonacci(n - 1); } // Iterative // O(n) public int fibonacci(int n) { if (n <= 0) return 0; if (n == 1) return 1; if (n == 2) return 2; // last, cur, next int last = 1; int cur = 2; for (int i = 3 ; i <= n ; i ++) { int temp = cur; cur = cur + last; last = temp; } return cur; }
[Twitter] Fibonacci Sequence
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。