在英语面试中可能需要 用英语表达算法的时间复杂度,这篇博文是学习后自我训练的笔记,用学过的英语来描述算法的时间复杂度。
for (int x = 0; x < n; x++) { //statement(s) that take constant time }
The initialization statement assign 0 to x runs once.
Java for loop increments the value x by 1 in every iteration.So the x is first 0,then 1,then 2,...,then n-1.
The increment statement xplusplus runs n times.
The comparison statement x is less than n runs n plus 1 time.
Summing them up, we get a running time complexity of for loop of n + n + 1 + 1 = 2*n + 2
The statements inside the loop runs n times, supposing these statements account for a constant running time of c in each iteration, they account for a running time of c*n throughout the loop's lifetime.Hence the running time complexity is XXX
for (int x = 0; x < n; x+=k) { //statement(s) that take constant time }
The initialization statement runs once.
The incrementation part x+k runs floor(n/k) times
The comparision statement x<n runs the same time as the incrementation part and one more time in the last iteration.
The inside the loop runs c * floor(n/k) times.
Summing them up, the running time complexity is 1 + n/k + n/k + 1 + c * n/k = (c+2)/k* n + 2
Dropping the leading constants (c+2)/k ==> n + 2
Dropping the lower order items ==> O(n)
for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ //Statement(s) that take(s) constant time } }
The inner loop runs (1+1+m+m)+c*m = (2m+2)+cm
The outer loop runs (1+1+n+n) + n(2m+2+cm) = (2+c)nm+4n+2 ,which is O(nm)
for (int i=0; i<n; i++){ for (int j=0; j<i; j++){ //Statement(s) that take(s) constant time } }
Let's start with the inner loop.
The initialization statement j = 0 runs n times throughout the whole lifetime.
The comparison statement j < i runs different times when i is set to different value. For example, the first time when i is 0,j<i runs once, the second time when i is 1, the statement runs 2, so when i is n-1, the statement runs n times. So, this statement runs 1+2+...+n times,which is(1+n)*n/2 times.
The increment statement j++ runs 0 + 1+2+...+n-1 times,which is (n-1)*n/2
The statement inside the inner loop runs also c(n-1)n/2 times
As for the outer loop, the statements runs a total of 2n+2 times
Hence, the running time complexity is n+(1+n)n/2 + (n-1)n/2 + c(n-1)n/2 + 2n+2 which is O(n^2)