509. 斐波那契数

 

 

老题目了,使用迭代可解(不建议用递归,会产生较多冗余计算)

时间O(n),空间O(1)

    public int fib(int n) {
        if (n<2) return n;
        int i=0,j=1,count=2;
        while(count<=n){
            int temp = j;
            j=i+j;
            i=temp;
            count++;
        }
        return j;
    }

 

posted @ 2021-04-14 10:34  jchen104  阅读(22)  评论(0编辑  收藏  举报