今天学习到一个有意思的算法结论
如果 T(N) ~ aN^b * logN,那么 T(2N)/T(N) ~ 2^b。
实验对象:ThreeSum算法
时间复杂度为O(n^3)
public interface ThreeSum {
int count(int[] nums);
}
public class ThreeSumSlow implements ThreeSum {
@Override
public int count(int[] nums) {
int N = nums.length;
int cnt = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
for (int k = j + 1; k < N; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
cnt++;
}
}
}
}
return cnt;
}
}
时间测试方法
public class StopWatch {
private static long start;
public static void start() {
start = System.currentTimeMillis();
}
public static double elapsedTime() {
long now = System.currentTimeMillis();
return (now - start) / 1000.0;
}
}
public class RatioTest {
public static void main(String[] args) {
int N = 500;
int loopTimes = 7; //循环次数
double preTime = -1; //每次循环的起始时间
while (loopTimes-- > 0) {
int[] nums = new int[N];
StopWatch.start();
ThreeSum threeSum = new ThreeSumSlow();
int cnt = threeSum.count(nums);
System.out.println(cnt);
double elapsedTime = StopWatch.elapsedTime(); //每次循环的结束时间
double ratio = preTime == -1 ? 0 : elapsedTime / preTime;
System.out.println(N + " " + elapsedTime + " " + ratio);//倍率
preTime = elapsedTime;
N *= 2;
}
}
}
实验结果
确实如同开始的结论,2^3 == > a * O(n^3) * logn