【问题标题】:two-sum algorithm complexity二和算法复杂度
【发布时间】:2015-04-17 19:46:33
【问题描述】:

下面的代码检查数组中任何一对数字的总和是否为零。我试图通过考虑主要操作(如变量声明、赋值、比较、增量、数组访问等)的多少次来锻炼复杂性。通常复杂性是 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++;

【问题讨论】:

  • 您需要大 O 复杂度还是精确复杂度?
  • 我的 O 复杂度很大,它是 O(N^2)。
  • 如果您对两个数组进行排序 (O(N log N)),您将能够在 O(N) 时间内检查总和。

标签: algorithm time-complexity


【解决方案1】:

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

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

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

该表达式简化为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2013-11-01
    相关资源
    最近更新 更多