循环中最糟糕的空间复杂性,它创建每个迭代

发布于 2025-01-25 09:47:36 字数 350 浏览 3 评论 0原文

无论是使用的算法总量的总和,还是仅在关键时间(最糟糕的时)消耗的空间,我都在努力找到适当的最差空间复杂性定义。

例如:

void myFunc(n) {
  for(int j = 0; j < n ; ++j) {
     int* myTab = malloc(n*sizeof(int));
     for(int i = 0; i < n; ++i) {
        myTab[i] = 1;
     }
      free(myTab);
   }
}

对于第一个定义,它大致是o(n²),对于第二个定义 o(n)

I am struggling to find a proper definition of worst space complexity whether it is the sum of the total amount of the algorithm used or if it is only the space consumed by the algorithm at a critical time, the worst one.

As an example:

void myFunc(n) {
  for(int j = 0; j < n ; ++j) {
     int* myTab = malloc(n*sizeof(int));
     for(int i = 0; i < n; ++i) {
        myTab[i] = 1;
     }
      free(myTab);
   }
}

For the first definition it is roughly O(N²) and for the second one O(N).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不必了 2025-02-01 09:47:36

它将是o(n)。分配完成后,您将明确释放内存。我同意malloc的内部工作原理是有用的,但是假设正常实现不足以更改空间复杂性(用于跟踪o(o(n))内存分配它保留o(n^2)元数据的数量 - 只是一个奇怪的例子)。

一个有趣的观点,可以清除您的想法。如果您评论此免费(..)行,则空间复杂性将为o(n^2)。这就是所谓的内存泄漏。

It would be O(n). You are explicitly freeing up the memory after the assignment is done. I agree the inner workings of the malloc would be useful but assuming a normal implementation which doesn't use memory enough to change the space complexity ( For tracking O(n) memory allocation it keeps O(n^2) amounts of metadata - just a weird example).

An interesting point, to clear up your idea. If you comment out this free(..) line, then the space complexity would be O(n^2). This is what is known as memory leakage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文