什么是菲波那切数列?自己google一下,面试题里面经常遇到,考试递归算法用的。

在菲波那切数列中用递归不太好。第三种算法最好。

第一 递归算法最差了,不想说。测试一下,当N=6000时,半天出不来数据,有想砸电脑的冲动。

第二 数组 在N变大后,空间浪费严重。

第三 队列 最好 只使用2个队列的空间,时间复杂度O(1) 常数级。

1 递归算法 最差的算法 也是比较经典的 得会
class Solution {
public int fib(int N) {
if(N==1){
return 1;
}
if(N<=0){
return 0;
}
return fib(N-1)+fib(N-2);
}
}
2 使用数组 time:O(n)   space:O(n)
class Solution {
public int fib(int N) {
if(N<=0){
return 0;
}
if(N<2){
return 1;
}
int[] nums=new int[N+1];
nums[0]=0;
nums[1]=1;
for(int i=2;i<N+1;i++){
nums[i]=nums[i-1]+nums[i-2];
}
return nums[N];
} }

3. 使用队列 先进先出 time:O(n)   space:O(1)

class Solution {
public int fib(int N) {
if(N<=0){
return 0;
}
if(N<2){
return 1;
}
Queue<Integer> queue=new LinkedList<>();
queue.offer(0);
queue.offer(1);
for(int i=2;i<N;i++){
queue.offer(queue.poll()+queue.peek());
}
return queue.poll()+queue.poll();
}
}

最新文章

  1. CS193P - 2016年秋 第一讲 课程简介
  2. queue
  3. 重构Web Api程序(Api Controller和Entity)续篇
  4. poj3295
  5. shell脚本之if语句
  6. spring3-hibernate3整合
  7. linux 病毒 sfewfesfs
  8. linux安装ruby
  9. 使用 Tomcat 7 新的连接池 —— Tomcat jdbc pool
  10. [jQuery] 使用jQuery printPage plugin打印其他頁面內容
  11. 功能和形式的反思sql声明 一个
  12. C++中printf和scanf的用法
  13. 微信小程序外包 就找北京动软 专业承接微信小程序定制
  14. docker 列出每个容器的IP
  15. 安装Python 库软件时提示&quot;setuptools must be installed to install from a source distribution&quot;错误
  16. html中&amp;lt;a&amp;gt;标签的种类
  17. web.config 加密/解密 正确版
  18. ABAP中不修改内表参照的结构,给内表/结构体增加字段
  19. easyui 获取特定页签tab
  20. 使用hibernate从一方获取多方信息时报错:org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role

热门文章

  1. 01二维背包+bitset优化——hdu5890
  2. NX二次开发-uc1600字符串对话框
  3. NX二次开发-算法篇-判断找到两个数组里不相同的对象
  4. flutter 超出俩行点点点
  5. 在jsp页面直接读取mysql数据库显示数据
  6. Python3 From Zero——{最初的意识:008~初级实例演练}
  7. &lt;爬虫实战&gt;糗事百科
  8. 调用第三方jar包_md5加密
  9. 9.ActiveMQ理论
  10. npm -v 报错:cannot find module &#39;core-util-is&#39;