这里列出了一些难做的题或是易错的题,简单的我就没有过多的解释,但是如果大家有任何问题都可以私信我或是评论一下,我会尽量即时的解答问题或是疑问的。
int x=0;
for(int i=4*n; i>=1; i--)
x=x+2*i;
O(n)
The loop runs O(n) times and does O(1) work per iteration.
int z=0;
int x=0;
for (int i=1; i<=n; i=i*3){
z = z+5;
z++;
x = 2*x;
}
O(log n)
Think about the values of i as the loop progresses. It will take on the series of values 1, 3, 9, 27, 81, 243, ..., 3k. Since i is tripling on each iteration, it takes on successive powers of three.
The loop clearly only does O(1) work per iteration, so the main
question here is how many total iterations there will be. The loop
will stop when i > n. If we let k be some arbitrary iteration of the
loop, the value of i on iteration k will be 3k. The loop stops when
3k > n, which happens when k > log3 n. Therefore, the number of
iterations is only O(log n)
int y=0;
for(int j=1; j*j<=n; j++)
j <= (n)^1/2 y++;
O(√n)
Notice that j is still growing linearly, but the loop runs as long as
j2 ≤ n. This means that as soon as j exceeds √ n, the loop will
stop. Therefore, there will only be O(√n) iterations of the loop,
and since each one does O(1) work, the total work done is O(√n)
int b=0; //constant
for(int i=n; i>0; i--)
for(int j=0; j<i; j++)
b=b+5;
O(n^2)
The most accurate answer would be O(n2)
int y=1;
int j=0;
for(j=1; j<=2n; j=j+2)
y=y+i;
int s=0;
for(i=1; i<=j; i++)
s++;
O(n)
int b=0;
for(int i=0; i<n; i++)
for(int j=0; j<i*n; j++)
b=b+5;
The inner loop will run 0 + n + 2n + 3n + 4n + ... + n(n-1) = n(0 + 1
+ 2 + ... + n - 1) times, so the total work done is O(n3). You
shouldn‘t multiply by the number of times the outer loop runs because
you‘re already summing up across all iterations. The most accurate
runtime would be O(n3)
int t=0;
for(int i=1; i<=n; i++)
for(int j=0; j*j<4*n; j++)
for(int k=1; k*k<=9*n; k++)
t++;
Look at the second loop. This actually runs O(√n) times using the
same logic as one of the earlier parts. That third inner loop also
runs O(√n) times, and so the total work done will be O(n2)
int a = 0;
int k = n*n;
while(k > 1)
{
for (int j=0; j<n*n; j++)
{ a++; }
k = k/2;
}
The outer loop starts with k initialized to n2, but notice that k is
halved on each iteration. This means that the number of iterations of
the outer loop will be log (n2) = 2 log n = O(log n), so the outer
loop runs only O(log n) times. That inner loop does do O(n2) work, so
the total runtime is O(n^2 log n)
int i=0, j=0, y=0, s=0;
for(j=0; j<n+1; j++)
y=y+j;
for(i=1; i<=y; i++)
s++;
O(n^3)