0%

1.Time and Space Complexity

1.Time Complexity

A indicator to evaluate the time cost of an algorithm.

1.1. O(1)

1
print("Hello World!")

1.2. O(n)

1
2
for i in range(n):
print(i)

1.3. O()

1
2
3
for i in range(n):
for j in range(n):
print(i,j)

1.4. O(logn)

1
2
3
4
n = 32
while n > 1:
n = n/2
print(n)

1.5. Common time complexity by order

2.Space Complexity

A indicator to evaluate the space cost of an algorithm.

2.1. O(1)

1
2
3
i = 1
j = 1
...

2.2. O(n)

1
list(range(n))

2.3. O(nm)

1
2
import numpy as np
np.random.rand(n, m)

3. Use more Space to save Time

As time is more expensive than memory, we should use memory to save time(if applicable).

  • list: search, insert slower, less memory consuming
  • dict: search, insert faster, more memory consuming