1. 程式人生 > 實用技巧 >資料結構-斐波那契數

資料結構-斐波那契數

demo01.java
package com.sjjg;

public class demo01 {

        /* 0 1 2 3 4 5
         * 0 1 1 2 3 5 8 13 ....
         */

        // O(2^n)
        public static int fib1(int n) {
            if (n <= 1) return n;
            return fib1(n - 1) + fib1(n - 2);
        }

        // O(n)
        public static int fib2(int n) {
            if (n <= 1) return n;

            int first = 0;
            int second = 1;
            for (int i = 0; i < n - 1; i++) {
                int sum = first + second;
                first = second;
                second = sum;
            }
            return second;
        }

        public static int fib3(int n) {
            if (n <= 1) return n;

            int first = 0;
            int second = 1;
            while (n-- > 1) {
                second += first;
                first = second - first;
            }
            return second;
        }


        public static void main(String[] args) {
            int n = 45;

//            System.out.println(fib2(70));
            //System.out.println(fib3(n));

		TimeTool.test("fib1", new TimeTool.Task() {
			public void execute() {
				System.out.println(fib1(n));
			}
		});

		TimeTool.test("fib2", new TimeTool.Task() {
			public void execute() {
				System.out.println(fib2(n));
			}
		});
        }
    }

輸出:
【fib1】
開始:16:04:31.033
1134903170
結束:16:04:35.223
耗時:4.19秒
-------------------------------------
【fib2】
開始:16:04:35.224
1134903170
結束:16:04:35.224
耗時:0.0秒
-------------------------------------

程序已結束,退出程式碼 0
TimeTool.java
package com.sjjg;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeTool {
    private static final SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss.SSS");

    public interface Task {
        void execute();
    }

    public static void test(String title, Task task) {
        if (task == null) return;
        title = (title == null) ? "" : ("【" + title + "】");
        System.out.println(title);
        System.out.println("開始:" + fmt.format(new Date()));
        long begin = System.currentTimeMillis();
        task.execute();
        long end = System.currentTimeMillis();
        System.out.println("結束:" + fmt.format(new Date()));
        double delta = (end - begin) / 1000.0;
        System.out.println("耗時:" + delta + "秒");
        System.out.println("-------------------------------------");
    }
}