mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 23:16:28 +08:00
a005c6ebd3
* Update avatar's link in the landing page * Bug fixes * Move assets folder from overrides to docs * Reduce figures' corner radius * Update copyright * Update header image * Krahets -> krahets * Update the landing page
90 lines
1.8 KiB
Python
90 lines
1.8 KiB
Python
"""
|
|
File: space_complexity.py
|
|
Created Time: 2022-11-25
|
|
Author: krahets (krahets@163.com)
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.append(str(Path(__file__).parent.parent))
|
|
from modules import ListNode, TreeNode, print_tree
|
|
|
|
|
|
def function() -> int:
|
|
"""函数"""
|
|
# 执行某些操作
|
|
return 0
|
|
|
|
|
|
def constant(n: int):
|
|
"""常数阶"""
|
|
# 常量、变量、对象占用 O(1) 空间
|
|
a = 0
|
|
nums = [0] * 10000
|
|
node = ListNode(0)
|
|
# 循环中的变量占用 O(1) 空间
|
|
for _ in range(n):
|
|
c = 0
|
|
# 循环中的函数占用 O(1) 空间
|
|
for _ in range(n):
|
|
function()
|
|
|
|
|
|
def linear(n: int):
|
|
"""线性阶"""
|
|
# 长度为 n 的列表占用 O(n) 空间
|
|
nums = [0] * n
|
|
# 长度为 n 的哈希表占用 O(n) 空间
|
|
hmap = dict[int, str]()
|
|
for i in range(n):
|
|
hmap[i] = str(i)
|
|
|
|
|
|
def linear_recur(n: int):
|
|
"""线性阶(递归实现)"""
|
|
print("递归 n =", n)
|
|
if n == 1:
|
|
return
|
|
linear_recur(n - 1)
|
|
|
|
|
|
def quadratic(n: int):
|
|
"""平方阶"""
|
|
# 二维列表占用 O(n^2) 空间
|
|
num_matrix = [[0] * n for _ in range(n)]
|
|
|
|
|
|
def quadratic_recur(n: int) -> int:
|
|
"""平方阶(递归实现)"""
|
|
if n <= 0:
|
|
return 0
|
|
# 数组 nums 长度为 n, n-1, ..., 2, 1
|
|
nums = [0] * n
|
|
return quadratic_recur(n - 1)
|
|
|
|
|
|
def build_tree(n: int) -> TreeNode | None:
|
|
"""指数阶(建立满二叉树)"""
|
|
if n == 0:
|
|
return None
|
|
root = TreeNode(0)
|
|
root.left = build_tree(n - 1)
|
|
root.right = build_tree(n - 1)
|
|
return root
|
|
|
|
|
|
"""Driver Code"""
|
|
if __name__ == "__main__":
|
|
n = 5
|
|
# 常数阶
|
|
constant(n)
|
|
# 线性阶
|
|
linear(n)
|
|
linear_recur(n)
|
|
# 平方阶
|
|
quadratic(n)
|
|
quadratic_recur(n)
|
|
# 指数阶
|
|
root = build_tree(n)
|
|
print_tree(root)
|