zoukankan      html  css  js  c++  java
  • 菲波那切数列(Fibonacci Number)

    什么是菲波那切数列?自己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();
        }
    }
  • 相关阅读:
    092 Reverse Linked List II 反转链表 II
    091 Decode Ways 解码方法
    090 Subsets II 子集 II
    089 Gray Code 格雷编码
    088 Merge Sorted Array 合并两个有序数组
    bzoj1218: [HNOI2003]激光炸弹
    bzoj1293: [SCOI2009]生日礼物
    bzoj3438: 小M的作物
    bzoj2565: 最长双回文串
    bzoj3172: [Tjoi2013]单词
  • 原文地址:https://www.cnblogs.com/zhangyuanbo12358/p/10898153.html
Copyright © 2011-2022 走看看