题目
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
1
2 F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
1
2 输入:n = 2
输出:1示例 2:
1
2 输入:n = 5
输出:5提示:
0 <= n <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
需要注意的点:
- 需要取模,由于斐波那契数列递增,我们只要把每一个新求出的值取模就可以(如果需要)。
1 | class Solution { |
- 时间复杂度$O(N)$
- 空间复杂度$O(1)$
总结
求余运算规则:
设正整数 x, y, p,有:
$$
(x+y)%p=(x%p+y%p)%p
$$
也就是我们之前想的只需对两数之和取余即可。