Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.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_Complexity Theory - Fatal编程技术网

Algorithm 这个函数的复杂性是什么?

Algorithm 这个函数的复杂性是什么?,algorithm,complexity-theory,Algorithm,Complexity Theory,在我的采访中,我总是提供这样的解决方案,但我不确定其复杂性是O(n^2),O(nlogn) (i=0;i

在我的采访中,我总是提供这样的解决方案,但我不确定其复杂性是O(n^2),O(nlogn)

(i=0;i { 对于(j=i;j让我们分析一下。。外部循环将运行
limit

First iteration of outer loop, i=0.. Inner loop runs limit times..
Second iteration of outer loop, i=1.. Inner loop runs limit-1 times.. 
.
.
.
.
Limit-th iteration of outer loop, i=limit-1.. Inner loop runs 1 time.. 

这给了我们一个复杂度
O(limit)*O(limit-1)*O(limit-2)*..*O(1)
,这反过来又使得这段代码的复杂度
O(n2)

让我们来分析一下。。外部循环将运行
limit

First iteration of outer loop, i=0.. Inner loop runs limit times..
Second iteration of outer loop, i=1.. Inner loop runs limit-1 times.. 
.
.
.
.
Limit-th iteration of outer loop, i=limit-1.. Inner loop runs 1 time.. 

这给了我们一个复杂度
O(limit)*O(limit-1)*O(limit-2)*..*O(1)
,这又使得这段代码的复杂度
O(n2)
这个复杂度当然是O(N^2)。为什么,让我们用演绎的方法简单地分析一下

    Limit = 10, the iterations are = 10 + 9 + 8 + 7 + ... + 1 = 10*(10+1) / 2
    Limit = 20, the iterations are = 20 + 19 + 18 + ... + 1 = 20*(20+1) / 2
    .
    .
    .
    Limit = N, the iterations are = N + N-1 + N-2 + ... + 1 = (N)(N+1)/2 
    In big-Oh notation, its complexity is O( (N)(N+1)/2 ) = O( (N^2 + N) / 2 ) which gives O(N^2)

这种复杂性当然是O(N^2)。为什么,让我们用演绎的方法简单地分析一下

    Limit = 10, the iterations are = 10 + 9 + 8 + 7 + ... + 1 = 10*(10+1) / 2
    Limit = 20, the iterations are = 20 + 19 + 18 + ... + 1 = 20*(20+1) / 2
    .
    .
    .
    Limit = N, the iterations are = N + N-1 + N-2 + ... + 1 = (N)(N+1)/2 
    In big-Oh notation, its complexity is O( (N)(N+1)/2 ) = O( (N^2 + N) / 2 ) which gives O(N^2)

只是为了理解,将限制设为6。现在,我可以从0到5,j可以从i到5。 当i=0 j=0到5时, i=1 j=1到5, i=2 j=2到5, i=3 j=3到5, i=4j=4到5, i=5j=5

因此,程序的“做点什么”部分运行5、4、3、2和1次。 这意味着限值=6的总次数为15次。或者n(n+1)/2倍于从1到n的数字之和。 (假设极限由n表示)


我知道这并不完全是n^2的复杂性,但当n变得更大时,n^2项将占主导地位。因此,在我看来,它是O(n^2)

为了理解,将极限值设为6。现在,我可以从0到5,j可以从i到5。 当i=0 j=0到5时, i=1 j=1到5, i=2 j=2到5, i=3 j=3到5, i=4j=4到5, i=5j=5

因此,程序的“做点什么”部分运行5、4、3、2和1次。 这意味着限值=6的总次数为15次。或者n(n+1)/2倍于从1到n的数字之和。 (假设极限由n表示)


我知道这并不完全是n^2的复杂性,但当n变得更大时,n^2项将占主导地位。因此,在我看来,它是O(n^2)

你对你的回答有什么理由?怎么解释?它的任何部分都是对数的吗?我决定它是O(N^2),但我不确定,因为第二个循环不会重复N次?有一种知道的方法可以知道最终答案,而不知道“做某事”的复杂性,但首先要确定“做某事”的次数会的。你的回答有什么理由?O(N Log N)是多少?它的任何部分都是对数的吗?我确定它是O(N^2),但我不确定,因为第二个循环不会重复N次?有一种知道的方法可以知道最终答案,而不知道“做某事”的复杂性,但首先要确定“做某事”要做多少次。不仅仅是
O(N^2)
在你看来:“当n变得更大时,
n^2
术语将占主导地位`是
O(n^2)
的定义。所以你很在行。不仅仅是
O(n^2)
在你看来:“当n变得更大时,
n^2
术语将占主导地位`是
O(n^2)
的定义。你说得对。