To prove safety offer face questions 10 (java version): Fibonacci number

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91384604

welcome to my blog

To prove safety offer face questions 10 (java version): Fibonacci number

Title Description

We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0).
n <= 39

Thinking

  • Recursive solution there will be a lot of repeat
  • Using a cyclic solve the first two identify the current note item corresponding to the code is fibMinus1, fibMinus2

the complexity

public class Solution {
    public int Fibonacci(int n) {
        // 健壮性判断
        if(n < 0)
            return -1;
        // 正式执行
        int[] result = {0,1};
        if(n<2)
            return result[n];
        int fibResult=0;
        int fibMinus1=1;
        int fibMinus2=0;
        for(int i=2; i<=n; i++){
            fibResult = fibMinus1 + fibMinus2;
            fibMinus2 = fibMinus1;
            fibMinus1 = fibResult;
        }
        return fibResult;
    }
}

/*
// 递归解法
public class Solution{
    public int Fibonacci(int n){
        return n<0? 0: n+Fibonacci(n-1);
    }
}

*/

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91384604