N²/2 - N/2 (N²)/2 N/2 1/2lim ────────── = lim ( ────── - ─── ) = lim ─── = 1/2N→∞ N² N→∞ N² N² N→∞ 1┕━━━┙this is 0 in the limit of N→∞:graph it, or plug in a really large number for N
for(i=0; i<A; i++) // A * ...some O(1) operation // 1
--> A*1 --> O(A) time
visualization:
|<------ A ------->|1 2 3 4 5 x x ... x
other languages, multiplying orders of growth:javascript, O(A) time and spacesomeListOfSizeA.map((x,i) => [x,i])python, O(rows*cols) time and space[[r*c for c in range(cols)] for r in range(rows)]
示例2:
for every x in listOfSizeA: // A * (...some O(1) operation // 1some O(B) operation // Bfor every y in listOfSizeC: // C * (...some O(1) operation // 1))
--> O(A*(1 + B + C))O(A*(B+C)) (1 is dwarfed)
visualization:
|<------ A ------->|1 x x x x x x ... x
2 x x x x x x ... x ^3 x x x x x x ... x |4 x x x x x x ... x |5 x x x x x x ... x B <-- A*Bx x x x x x x ... x |................... |x x x x x x x ... x v
x x x x x x x ... x ^x x x x x x x ... x |x x x x x x x ... x |x x x x x x x ... x C <-- A*Cx x x x x x x ... x |................... |x x x x x x x ... x v
示例3:
function nSquaredFunction(n) {total = 0for i in 1..n: // N *for j in 1..n: // N *total += i*k // 1return total}// O(n^2)
function nCubedFunction(a) {for i in 1..n: // A *print(nSquaredFunction(a)) // A^2}// O(a^3)
如果我们做一些稍微复杂的事情,你仍然可以直观地想象发生了什么:
for x in range(A):for y in range(1..x):simpleOperation(x*y)
x x x x x x x x x x |x x x x x x x x x |x x x x x x x x |x x x x x x x |x x x x x x |x x x x x |x x x x |x x x |x x |x___________________|
<----------------------------- N ----------------------------->x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x xx x x x x x x x x x x x x x x xx x x x x x x xx x x xx xx
我们可以重新排列它,看到它是O(N):
<----------------------------- N ----------------------------->x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x xx x x x x x x x x x x x x x x x|x x x x x x x x|x x x x|x x|x
或者您可以对数据进行log(N)次传递,总时间为O(N*log(N)):
<----------------------------- N ----------------------------->^ x x x x x x x x x x x x x x x x|x x x x x x x x x x x x x x x x| x x x x x x x x|x x x x x x x x|x x x x x x x x|x x x x x x x xlgN x x x x|x x x x|x x x x|x x x x|x x x x|x x x x|x x x x|x x x x| x x|x x|x x|x x|x x|x x|x x|x x|x x|x x|x x|x x|x x|x x|x x|x xv x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x
无关但值得一提的是:如果我们执行哈希(例如字典/哈希表查找),那是O(1)的因子。这很快。
[myDictionary.has(x) for x in listOfSizeA]\----- O(1) ------/
--> A*1 --> O(A)
大多数时候,人们没有意识到工作中有不止一个变量。例如,在字符串搜索算法中,你的算法可能需要时间O([length of text] + [length of query]),即它在像O(N+M)这样的两个变量中是线性的。其他更天真的算法可能是O([length of text]*[length of query])或O(N*M)。忽略多个变量是我在算法分析中看到的最常见的疏忽之一,在设计算法时可能会阻碍你。