数据结构:菲波那切数列

package test;

public class test {
	public static int fib1(int n) {
		if (n<=1) return n;
			return fib1(n-1)+fib1(n-2);
	}
	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 void main(String[] args) {
		System.out.println(fib2(64));
	}
}

fib1不能正常执行,fib2可以(大致原因:fib1执行速度慢,fib2执行速度快)

这里有一个小工具:(测算法运行时间)

package test;

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("-------------------------------------");
	}


}

代码改动后:

package test;

import test.TimeTool.Task;

public class test {
	public static int fib1(int n) {
		if (n<=1) return n;
			return fib1(n-1)+fib1(n-2);
	}
	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 void main(String[] args) {
		TimeTool.test("fib1",new Task() {
			public void execute() {
				System.out.println(fib1(30));   //将测试的代码写在这里面
			}
		});
		TimeTool.test("fib2",new Task() {
			public void execute() {
				System.out.println(fib2(30));
			}
		});
	}
}

测量这两个算法的时间。

运行结果:

很明显fib2快。

有一点需要注意:

这里面写测试方法。

也可以用现代来解决。

发布了91 篇原创文章 · 获赞 8 · 访问量 4747

猜你喜欢

转载自blog.csdn.net/niuxikun/article/details/104527924