So the answer to this question, same as the last one.
Big O of n squared.
That is, this piece of code is also a quad-, has quadratic running time.
So what I hope was clear was that, you know? Whatever the running time of this piece of code is.
It's proportional to the number of iterations of this double four loop.
Like in all the examples, we do constant work per iteration.
We don't care about the constant.
It gets suppressed by the big O notation.
So, all we gotta do is figure out how many iterations there are of this double four loop.
My claim is that there's roughly n squared over two iterations of this double four loop.
There's a couple ways to see that.
Informally, we discussed how the difference between this code and the previous one, is that, instead of counting something twice, we're counting it once.
So that saves us a factor of two in the number of iterations.
Of course, this one half factor gets suppressed by the big O notation anyways.
So the big O, running time doesn't change.
A different argument would just say, you know? How many, there's one iteration for every distinct choice of i and j of indices between one and n.
And a simple counting argument.
Says that there's n choose 2 such choices of distinct i and j, where n choose 2 is the number n times n minus 1 over 2.
And again, supressing lower-order terms and the constant factor, we still get a quadratic dependence on the length of the input array A.
So that wraps up some of the sort of just simple basic examples.
I hope this gets you oriented, you have a strong intuitive sense for what big O notation is trying to accomplish.
And how it's defined mathematically.
Let's now move onto both the mathematical developments and some more interesting algorithms.
因此驮履,這個問題的答案與上一個相同谭网。
n的大O平方积糯。
也就是說媚污,這段代碼也是四倍的,具有二次運行時間躲叼。
所以我希望清楚的是蔬捷,您知道嗎?無論這段代碼的運行時間如何董习。
它與這個雙四循環(huán)的迭代次數(shù)成正比烈和。
像所有示例一樣,我們在每次迭代中都做不斷的工作皿淋。
我們不在乎常量招刹。
大號O表示抑制了它恬试。
因此,我們要做的就是找出這個雙四循環(huán)的迭代次數(shù)疯暑。
我的主張是在這個雙四循環(huán)的兩次迭代中大約有n平方训柴。
有幾種方法可以看到這一點。
非正式地妇拯,我們討論了此代碼與上一個代碼之間的區(qū)別是幻馁,我們沒有計算兩次,而是計算了一次越锈。
這樣可以為我們節(jié)省兩倍的迭代次數(shù)仗嗦。
當然,無論如何瞪浸,這一二分之一因素會被大的O表示法抑制儒将。
因此,大O对蒲,運行時間不會改變钩蚊。
一個不同的論點只會說,你知道嗎蹈矮?多少砰逻,索引i和j在n和n之間的每個不同選擇都有一個迭代。
還有一個簡單的計數(shù)論點泛鸟。
假設有n個選擇這樣的i和j的2個選擇蝠咆,其中n選擇2是n乘以n減去1等于2的數(shù)字。
再次北滥,抑制低階項和常數(shù)因子刚操,我們仍然對輸入數(shù)組A的長度有二次依賴性。
這樣就構成了一些簡單的基本示例再芋。
我希望這能使您有方向菊霜,對大型O標記試圖完成的工作具有強烈的直覺感。
以及如何對其進行數(shù)學定義济赎。
現(xiàn)在鉴逞,讓我們繼續(xù)進行數(shù)學開發(fā)和一些更有趣的算法。