[剑指Offer]斐波那契数列

O(n)时间 O(1)空间实现:

写一个函数,输入n,求斐波那契数列的第n项。

package 斐波那契数列;

public class Solution {

    /** * 写一个函数,输入n,求斐波那契(Fibonacci) 数列的第n项 * * @param n * Fibonacci数的项数 * @return 第n项的结果 */
    public static long fibonacci(int n) {
        // 当输入非正整数的时候返回0
        if (n <= 0) {
            return 0;
        }
        // 输入1或者2的时候返回1
        if (n == 1 || n == 2) {
            return 1;
        }
        // 纪录前两个(第n-2个)的Fibomacci数的值
        long prePre = 1;
        // 纪录前两个(第n-1个)的Fibonacci数的值
        long pre = 1;
        // 纪录前两个(第n个)的Fibonacci数的值
        long current = 2;
        // 求解第n个的Fabonacci数的值
        for (int i = 3; i <= n; i++) {
            // 求第i个的Fibonacci数的值
            current = prePre + pre;
            // 更新纪录的结果,prePre原先纪录第i-2个Fibonacci数的值
            // 现在纪录第i-1个Fibonacci数的值
            prePre = pre;
            // 更新纪录的结果,pre原来纪录第i-1个Fibonacci数的值
            // 现在纪录第i个Fibonacci数的值
            pre = current;
        }
        // 返回所求的结果
        return current;
    }
}

你可能感兴趣的:(算法)