gpt4 book ai didi

algorithm - 二和算法复杂度

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:23:21 25 4
gpt4 key购买 nike

下面的代码检查数组中任何一对数字的总和是否为零。我正在尝试通过考虑变量声明、赋值、比较、递增、数组访问等主要操作的次数来计算复杂度。通常复杂度为 O(N^2),但当我必须考虑上面指定的操作。我应该如何处理这个问题?

int count = 0;
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++)
if(a[i] + a[j] == 0)
count++;

最佳答案

我将缩进代码并明确突出显示每个操作:

int count = 0; // <-- 1 operation

for(int i=0; i<N; i++) // <-- 2 operations per iteration
for(int j=i+1; j<N; j++) // <-- 2 operations per iteration
if(a[i] + a[j] == 0) // <-- 4 operations
count++; // <-- impossible to tell without knowing a. Counting as 1 operation

下面是计算操作总数的方法:

enter image description here

该表达式简化为:

enter image description here

这是你的答案。请注意,这是 O(N^2),这与您之前的观察结果一致。

关于algorithm - 二和算法复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29708134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com