【Lintcode】366. Fibonacci

题目地址:

https://www.lintcode.com/problem/fibonacci/description

求第 n n 个Fibonacci数。代码如下:

public class Solution {
    /**
     * @param n: an integer
     * @return: an ineger f(n)
     */
    public int fibonacci(int n) {
        // write your code here
        if (n == 1) {
            return 0;
        } else if (n == 2) {
            return 1;
        }
        
        int n1 = 0, n2 = 1;
        for (int i = 2; i < n; i++) {
            n2 += n1;
            n1 = n2 - n1;
        }
        
        return n2;
    }
}

时间复杂度 O ( n ) O(n)

发布了388 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105361581