程序运行时间与时间复杂度

引言

PAT考试对算法时间复杂度有考查,经常会有个别测试点数据量很大,而算法比较low的代码就会出现运行超时的问题,我也曾经经常被这种问题搞得头皮发麻。于是想测试一下PAT的OJ系统最大能承受O(n2)时间复杂度的算法的规模n大概是多少。

测试代码

#include<cstdio>
#include<time.h>
using namespace std;

int main() {
	clock_t t1, t2;
	t1 = clock();
	for (int i = 0; i < 10000; i++) {
		for (int j = 0; j < 10000; j++);
	}
	t2 = clock();
	printf("%.3f s\n",(double)(t2 - t1)/ CLOCKS_PER_SEC);
	
	t1 = clock();
	for (int i = 0; i < 100000; i++) {
		for (int j = 0; j < 100000; j++);
	}
	t2 = clock();
	printf("%.3f s",(double)(t2 - t1)/ CLOCKS_PER_SEC);
	return 0;
}

测试结果

在这里插入图片描述
可以发现,n=10000时循环体耗时210ms,而PAT时间限制一般为200ms,那么一般104规模的时间复杂度为O(n2)的程序是无法通过的,105就更别提了

但是,如果是下面这种,应该是勉强可以的~

for (int i = 0; i < 10000; i++) {
		for (int j = i; j < 10000; j++);
	}
发布了62 篇原创文章 · 获赞 7 · 访问量 3123

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104155591