根据条件,对数据进行操作,得到结果
好算法:用最短的时间,占用最少的内存得出结果
时间复杂度,空间复杂度
例子:求1到100的和
public class Compare {
//算1+100的效率
public static void main(String[] args) {
one();
two();
}
public static void one(){
long startTime=System.nanoTime();
int sum=0;
int b=100;
for (int i = 1; i <=100; i++) {
sum=sum+i;
}
System.out.println(sum);
long endTime=System.nanoTime();
System.out.println("方法1"+(endTime-startTime));
}
public static void two(){
long startTime=System.nanoTime();
//nanoTime() 返回最准确的可用系统计时器的当前值,以纳秒为单位。
//currentTimeMillis() 返回以毫秒为单位的当前时间。
int sum=0;
int b=100;
sum=(1+b)*b/2;
System.out.println(sum);
long endTime=System.nanoTime();
System.out.println("方法2"+(endTime-startTime));
}
}
输出结果
5050
方法1144200
5050
方法218900
这一个小小的算法,差了将近100万纳秒,但是当数据大的时候会更加明显。所以好的算法是很有必要的。
例子2:求10的阶乘
public class Compare {
public static void main(String[] args) {
long start1 = System.nanoTime();
int a = three(10);
System.out.println(a);
long end1 = System.nanoTime();
System.out.println("方法3" + (end1 - start1));
long start2 = System.nanoTime();
int b = four(10);
long end2 = System.nanoTime();
System.out.println(b);
System.out.println("方法4" + (end2 - start2));
}
public static int three(int a) {
if (a == 0) {
return 1;
}
return a * three(a - 1);
}
public static int four(int a) {
int m = 1;
for (int i = 1; i <= a; i++) {
m = m * i;
}
return m;
}
}
输出结果
3628800
方法3:175000
3628800
方法4:3000
运算效率差100多倍;
内存占用情况:
递归调用了十次方法,占用了10个单位内存;
for循环调用了一次方法,只占用一个单元内存;