The second forum offer to prove safety questions 10: Fibonacci number (JAVA version)

Topic: write a function, input n, seeking first Fibonacci number Fibonacci sequence of n items. Fibonacci series deed defined as follows:

1, the efficiency is very inefficient solution, discerning interviewer will not like

Recursive implementation:

public class Fibonacci {
    public long getNum(int n){
        if(n<=0){
            return 0;
        }else if(n==1){
            return 1;
        }else{
            return getNum(n-1)+getNum(n-2);
        }
    }
}

 

We find that there are a lot of nodes are duplicated in the Fengyun tree, and the number of nodes will repeat as n increases dramatically increase, which means that the amount will be calculated as n increases sharply increased. In fact, the time complexity of the calculation by the method of recursive n is incremented exponent. Readers may wish to seek the first 100 Fibonacci's try, feel this recursion will slow to what extent.

 

2, the interviewer looking for suitable solution:

In fact, the improved method is not complicated, saved the calculated intermediate term, reduce the number of calculations

 

public  class the fibonacci2 {
     public  Long getNum ( int n-) {
         IF (n-== 0 ) {
             return 0 ; 
        } 
        IF (n-==. 1 ) {
             return . 1 ; 
        } 
        int temp1 = 0; // n-2-value of the item 
        int temp2 of =. 1; // the n-1 value of the item 
        int result = 0; // save the intermediate results calculated 
        for ( int I = 2; I <= n-; I ++ ) { 
            result = temp1 + temp2 of; 
            temp1 =temp2;
            temp2=result;
        }
        return result;
    }
}

 

Guess you like

Origin www.cnblogs.com/xhlwjy/p/11259396.html