Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 二和算法复杂度_Algorithm_Time Complexity - Fatal编程技术网

Algorithm 二和算法复杂度

Algorithm 二和算法复杂度,algorithm,time-complexity,Algorithm,Time Complexity,下面的代码检查数组中任何一对数字的和是否等于零。我试图通过考虑变量的声明、值分配、比较、增量、数组访问等主要操作的复杂性来计算复杂性。通常,复杂性是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; 对于(int i=0;i我将缩进代

下面的代码检查数组中任何一对数字的和是否等于零。我试图通过考虑变量的声明、值分配、比较、增量、数组访问等主要操作的复杂性来计算复杂性。通常,复杂性是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;

对于(int i=0;i我将缩进代码并显式突出显示每个操作:

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

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