为什么这段代码中的时间复杂度为O(n ^ 2)?

编程入门 行业动态 更新时间:2024-10-24 22:24:54
本文介绍了为什么这段代码中的时间复杂度为O(n ^ 2)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只是不明白,为什么时间复杂度是O(n ^ 2)而不是O(n * logn)? 第二个循环每次递增2,所以它不是O(logn)吗?

I just didn't get it, why the time complexity is O(n^2) instead of O(n*logn)? The second loop is incrementing 2 each time so isn't it O(logn)?

void f3(int n){ int i,j,s=100; int* ar = (int*)malloc(s*sizeof(int)); for(i=0; i<n; i++){ s=0; for(j=0; j<n; j+=2){ s+=j; printf("%d\n", s); } free(ar); }

推荐答案

通过递增2而不是1,您正在执行以下N*N*(1/2).使用big(O)表示法时,您无需关心常数,因此它仍然是N * N.这是因为big(O)表示的是算法增长的复杂性.

By incrementing by two, rather than one, you're doing the following N*N*(1/2). With big(O) notation, you don't care about the constant, so it's still N*N. This is because big(O) notation reference the complexity of the growth of an algorithm.

更多推荐

为什么这段代码中的时间复杂度为O(n ^ 2)?

本文发布于:2023-11-30 17:16:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复杂度   这段   代码   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!