Remove `-> None` for Python functions

pull/654/head
krahets 1 year ago
parent ac0f405f9a
commit 90af225dae

@ -29,7 +29,7 @@ def extend(nums: list[int], enlarge: int) -> list[int]:
return res return res
def insert(nums: list[int], num: int, index: int) -> None: def insert(nums: list[int], num: int, index: int):
"""在数组的索引 index 处插入元素 num""" """在数组的索引 index 处插入元素 num"""
# 把索引 index 以及之后的所有元素向后移动一位 # 把索引 index 以及之后的所有元素向后移动一位
for i in range(len(nums) - 1, index, -1): for i in range(len(nums) - 1, index, -1):
@ -38,14 +38,14 @@ def insert(nums: list[int], num: int, index: int) -> None:
nums[index] = num nums[index] = num
def remove(nums: list[int], index: int) -> None: def remove(nums: list[int], index: int):
"""删除索引 index 处元素""" """删除索引 index 处元素"""
# 把索引 index 之后的所有元素向前移动一位 # 把索引 index 之后的所有元素向前移动一位
for i in range(index, len(nums) - 1): for i in range(index, len(nums) - 1):
nums[i] = nums[i + 1] nums[i] = nums[i + 1]
def traverse(nums: list[int]) -> None: def traverse(nums: list[int]):
"""遍历数组""" """遍历数组"""
count = 0 count = 0
# 通过索引遍历数组 # 通过索引遍历数组

@ -10,14 +10,14 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import * from modules import *
def insert(n0: ListNode, P: ListNode) -> None: def insert(n0: ListNode, P: ListNode):
"""在链表的节点 n0 之后插入节点 P""" """在链表的节点 n0 之后插入节点 P"""
n1 = n0.next n1 = n0.next
P.next = n1 P.next = n1
n0.next = P n0.next = P
def remove(n0: ListNode) -> None: def remove(n0: ListNode):
"""删除链表的节点 n0 之后的首个节点""" """删除链表的节点 n0 之后的首个节点"""
if not n0.next: if not n0.next:
return return

@ -30,13 +30,13 @@ class MyList:
raise IndexError("索引越界") raise IndexError("索引越界")
return self.__nums[index] return self.__nums[index]
def set(self, num: int, index: int) -> None: def set(self, num: int, index: int):
"""更新元素""" """更新元素"""
if index < 0 or index >= self.__size: if index < 0 or index >= self.__size:
raise IndexError("索引越界") raise IndexError("索引越界")
self.__nums[index] = num self.__nums[index] = num
def add(self, num: int) -> None: def add(self, num: int):
"""尾部添加元素""" """尾部添加元素"""
# 元素数量超出容量时,触发扩容机制 # 元素数量超出容量时,触发扩容机制
if self.size() == self.capacity(): if self.size() == self.capacity():
@ -44,7 +44,7 @@ class MyList:
self.__nums[self.__size] = num self.__nums[self.__size] = num
self.__size += 1 self.__size += 1
def insert(self, num: int, index: int) -> None: def insert(self, num: int, index: int):
"""中间插入元素""" """中间插入元素"""
if index < 0 or index >= self.__size: if index < 0 or index >= self.__size:
raise IndexError("索引越界") raise IndexError("索引越界")
@ -71,7 +71,7 @@ class MyList:
# 返回被删除元素 # 返回被删除元素
return num return num
def extend_capacity(self) -> None: def extend_capacity(self):
"""列表扩容""" """列表扩容"""
# 新建一个长度为原数组 __extend_ratio 倍的新数组,并将原数组拷贝到新数组 # 新建一个长度为原数组 __extend_ratio 倍的新数组,并将原数组拷贝到新数组
self.__nums = self.__nums + [0] * self.capacity() * (self.__extend_ratio - 1) self.__nums = self.__nums + [0] * self.capacity() * (self.__extend_ratio - 1)

@ -10,7 +10,7 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import * from modules import *
def pre_order(root: TreeNode) -> None: def pre_order(root: TreeNode):
"""前序遍历:例题一""" """前序遍历:例题一"""
if root is None: if root is None:
return return

@ -10,7 +10,7 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import * from modules import *
def pre_order(root: TreeNode) -> None: def pre_order(root: TreeNode):
"""前序遍历:例题二""" """前序遍历:例题二"""
if root is None: if root is None:
return return

@ -10,7 +10,7 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import * from modules import *
def pre_order(root: TreeNode) -> None: def pre_order(root: TreeNode):
"""前序遍历:例题三""" """前序遍历:例题三"""
# 剪枝 # 剪枝
if root is None or root.val == 3: if root is None or root.val == 3:

@ -16,7 +16,7 @@ def function() -> int:
return 0 return 0
def constant(n: int) -> None: def constant(n: int):
"""常数阶""" """常数阶"""
# 常量、变量、对象占用 O(1) 空间 # 常量、变量、对象占用 O(1) 空间
a = 0 a = 0
@ -30,7 +30,7 @@ def constant(n: int) -> None:
function() function()
def linear(n: int) -> None: def linear(n: int):
"""线性阶""" """线性阶"""
# 长度为 n 的列表占用 O(n) 空间 # 长度为 n 的列表占用 O(n) 空间
nums = [0] * n nums = [0] * n
@ -40,7 +40,7 @@ def linear(n: int) -> None:
mapp[i] = str(i) mapp[i] = str(i)
def linear_recur(n: int) -> None: def linear_recur(n: int):
"""线性阶(递归实现)""" """线性阶(递归实现)"""
print("递归 n =", n) print("递归 n =", n)
if n == 1: if n == 1:
@ -48,7 +48,7 @@ def linear_recur(n: int) -> None:
linear_recur(n - 1) linear_recur(n - 1)
def quadratic(n: int) -> None: def quadratic(n: int):
"""平方阶""" """平方阶"""
# 二维列表占用 O(n^2) 空间 # 二维列表占用 O(n^2) 空间
num_matrix = [[0] * n for _ in range(n)] num_matrix = [[0] * n for _ in range(n)]

@ -13,7 +13,7 @@ from modules import *
class GraphAdjList: class GraphAdjList:
"""基于邻接表实现的无向图类""" """基于邻接表实现的无向图类"""
def __init__(self, edges: list[list[Vertex]]) -> None: def __init__(self, edges: list[list[Vertex]]):
"""构造方法""" """构造方法"""
# 邻接表key: 顶点value该顶点的所有邻接顶点 # 邻接表key: 顶点value该顶点的所有邻接顶点
self.adj_list = dict[Vertex, Vertex]() self.adj_list = dict[Vertex, Vertex]()
@ -27,7 +27,7 @@ class GraphAdjList:
"""获取顶点数量""" """获取顶点数量"""
return len(self.adj_list) return len(self.adj_list)
def add_edge(self, vet1: Vertex, vet2: Vertex) -> None: def add_edge(self, vet1: Vertex, vet2: Vertex):
"""添加边""" """添加边"""
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2: if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
raise ValueError() raise ValueError()
@ -35,7 +35,7 @@ class GraphAdjList:
self.adj_list[vet1].append(vet2) self.adj_list[vet1].append(vet2)
self.adj_list[vet2].append(vet1) self.adj_list[vet2].append(vet1)
def remove_edge(self, vet1: Vertex, vet2: Vertex) -> None: def remove_edge(self, vet1: Vertex, vet2: Vertex):
"""删除边""" """删除边"""
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2: if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
raise ValueError() raise ValueError()
@ -43,14 +43,14 @@ class GraphAdjList:
self.adj_list[vet1].remove(vet2) self.adj_list[vet1].remove(vet2)
self.adj_list[vet2].remove(vet1) self.adj_list[vet2].remove(vet1)
def add_vertex(self, vet: Vertex) -> None: def add_vertex(self, vet: Vertex):
"""添加顶点""" """添加顶点"""
if vet in self.adj_list: if vet in self.adj_list:
return return
# 在邻接表中添加一个新链表 # 在邻接表中添加一个新链表
self.adj_list[vet] = [] self.adj_list[vet] = []
def remove_vertex(self, vet: Vertex) -> None: def remove_vertex(self, vet: Vertex):
"""删除顶点""" """删除顶点"""
if vet not in self.adj_list: if vet not in self.adj_list:
raise ValueError() raise ValueError()
@ -61,7 +61,7 @@ class GraphAdjList:
if vet in self.adj_list[vertex]: if vet in self.adj_list[vertex]:
self.adj_list[vertex].remove(vet) self.adj_list[vertex].remove(vet)
def print(self) -> None: def print(self):
"""打印邻接表""" """打印邻接表"""
print("邻接表 =") print("邻接表 =")
for vertex in self.adj_list: for vertex in self.adj_list:

@ -18,7 +18,7 @@ class GraphAdjMat:
# 邻接矩阵,行列索引对应“顶点索引” # 邻接矩阵,行列索引对应“顶点索引”
adj_mat: list[list[int]] = [] adj_mat: list[list[int]] = []
def __init__(self, vertices: list[int], edges: list[list[int]]) -> None: def __init__(self, vertices: list[int], edges: list[list[int]]):
"""构造方法""" """构造方法"""
self.vertices: list[int] = [] self.vertices: list[int] = []
self.adj_mat: list[list[int]] = [] self.adj_mat: list[list[int]] = []
@ -34,7 +34,7 @@ class GraphAdjMat:
"""获取顶点数量""" """获取顶点数量"""
return len(self.vertices) return len(self.vertices)
def add_vertex(self, val: int) -> None: def add_vertex(self, val: int):
"""添加顶点""" """添加顶点"""
n = self.size() n = self.size()
# 向顶点列表中添加新顶点的值 # 向顶点列表中添加新顶点的值
@ -46,7 +46,7 @@ class GraphAdjMat:
for row in self.adj_mat: for row in self.adj_mat:
row.append(0) row.append(0)
def remove_vertex(self, index: int) -> None: def remove_vertex(self, index: int):
"""删除顶点""" """删除顶点"""
if index >= self.size(): if index >= self.size():
raise IndexError() raise IndexError()
@ -58,7 +58,7 @@ class GraphAdjMat:
for row in self.adj_mat: for row in self.adj_mat:
row.pop(index) row.pop(index)
def add_edge(self, i: int, j: int) -> None: def add_edge(self, i: int, j: int):
"""添加边""" """添加边"""
# 参数 i, j 对应 vertices 元素索引 # 参数 i, j 对应 vertices 元素索引
# 索引越界与相等处理 # 索引越界与相等处理
@ -68,7 +68,7 @@ class GraphAdjMat:
self.adj_mat[i][j] = 1 self.adj_mat[i][j] = 1
self.adj_mat[j][i] = 1 self.adj_mat[j][i] = 1
def remove_edge(self, i: int, j: int) -> None: def remove_edge(self, i: int, j: int):
"""删除边""" """删除边"""
# 参数 i, j 对应 vertices 元素索引 # 参数 i, j 对应 vertices 元素索引
# 索引越界与相等处理 # 索引越界与相等处理
@ -77,7 +77,7 @@ class GraphAdjMat:
self.adj_mat[i][j] = 0 self.adj_mat[i][j] = 0
self.adj_mat[j][i] = 0 self.adj_mat[j][i] = 0
def print(self) -> None: def print(self):
"""打印邻接矩阵""" """打印邻接矩阵"""
print("顶点列表 =", self.vertices) print("顶点列表 =", self.vertices)
print("邻接矩阵 =") print("邻接矩阵 =")

@ -93,7 +93,7 @@ class HashMapOpenAddressing:
if pair not in [None, self.removed]: if pair not in [None, self.removed]:
self.put(pair.key, pair.val) self.put(pair.key, pair.val)
def print(self) -> None: def print(self):
"""打印哈希表""" """打印哈希表"""
for pair in self.buckets: for pair in self.buckets:
if pair is not None: if pair is not None:

@ -12,13 +12,13 @@ from modules import *
import heapq import heapq
def test_push(heap: list, val: int, flag: int = 1) -> None: def test_push(heap: list, val: int, flag: int = 1):
heapq.heappush(heap, flag * val) # 元素入堆 heapq.heappush(heap, flag * val) # 元素入堆
print(f"\n元素 {val} 入堆后") print(f"\n元素 {val} 入堆后")
print_heap([flag * val for val in heap]) print_heap([flag * val for val in heap])
def test_pop(heap: list, flag: int = 1) -> None: def test_pop(heap: list, flag: int = 1):
val = flag * heapq.heappop(heap) # 堆顶元素出堆 val = flag * heapq.heappop(heap) # 堆顶元素出堆
print(f"\n堆顶元素 {val} 出堆后") print(f"\n堆顶元素 {val} 出堆后")
print_heap([flag * val for val in heap]) print_heap([flag * val for val in heap])

@ -5,7 +5,7 @@ Author: timi (xisunyy@163.com)
""" """
def bubble_sort(nums: list[int]) -> None: def bubble_sort(nums: list[int]):
"""冒泡排序""" """冒泡排序"""
n = len(nums) n = len(nums)
# 外循环:未排序区间为 [0, i] # 外循环:未排序区间为 [0, i]
@ -17,7 +17,7 @@ def bubble_sort(nums: list[int]) -> None:
nums[j], nums[j + 1] = nums[j + 1], nums[j] nums[j], nums[j + 1] = nums[j + 1], nums[j]
def bubble_sort_with_flag(nums: list[int]) -> None: def bubble_sort_with_flag(nums: list[int]):
"""冒泡排序(标志优化)""" """冒泡排序(标志优化)"""
n = len(nums) n = len(nums)
# 外循环:未排序区间为 [0, i] # 外循环:未排序区间为 [0, i]

@ -5,7 +5,7 @@ Author: Krahets (krahets@163.com)
""" """
def bucket_sort(nums: list[float]) -> None: def bucket_sort(nums: list[float]):
"""桶排序""" """桶排序"""
# 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素 # 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
k = len(nums) // 2 k = len(nums) // 2

@ -5,7 +5,7 @@ Author: Krahets (krahets@163.com)
""" """
def counting_sort_naive(nums: list[int]) -> None: def counting_sort_naive(nums: list[int]):
"""计数排序""" """计数排序"""
# 简单实现,无法用于排序对象 # 简单实现,无法用于排序对象
# 1. 统计数组最大元素 m # 1. 统计数组最大元素 m
@ -25,7 +25,7 @@ def counting_sort_naive(nums: list[int]) -> None:
i += 1 i += 1
def counting_sort(nums: list[int]) -> None: def counting_sort(nums: list[int]):
"""计数排序""" """计数排序"""
# 完整实现,可排序对象,并且是稳定排序 # 完整实现,可排序对象,并且是稳定排序
# 1. 统计数组最大元素 m # 1. 统计数组最大元素 m

@ -5,7 +5,7 @@ Author: timi (xisunyy@163.com)
""" """
def insertion_sort(nums: list[int]) -> None: def insertion_sort(nums: list[int]):
"""插入排序""" """插入排序"""
# 外循环:已排序区间为 [0, i-1] # 外循环:已排序区间为 [0, i-1]
for i in range(1, len(nums)): for i in range(1, len(nums)):

@ -5,7 +5,7 @@ Author: timi (xisunyy@163.com)
""" """
def merge(nums: list[int], left: int, mid: int, right: int) -> None: def merge(nums: list[int], left: int, mid: int, right: int):
"""合并左子数组和右子数组""" """合并左子数组和右子数组"""
# 左子数组区间 [left, mid] # 左子数组区间 [left, mid]
# 右子数组区间 [mid + 1, right] # 右子数组区间 [mid + 1, right]
@ -36,7 +36,7 @@ def merge(nums: list[int], left: int, mid: int, right: int) -> None:
j += 1 j += 1
def merge_sort(nums: list[int], left: int, right: int) -> None: def merge_sort(nums: list[int], left: int, right: int):
"""归并排序""" """归并排序"""
# 终止条件 # 终止条件
if left >= right: if left >= right:

@ -23,7 +23,7 @@ class QuickSort:
nums[i], nums[left] = nums[left], nums[i] nums[i], nums[left] = nums[left], nums[i]
return i # 返回基准数的索引 return i # 返回基准数的索引
def quick_sort(self, nums: list[int], left: int, right: int) -> None: def quick_sort(self, nums: list[int], left: int, right: int):
"""快速排序""" """快速排序"""
# 子数组长度为 1 时终止递归 # 子数组长度为 1 时终止递归
if left >= right: if left >= right:
@ -67,7 +67,7 @@ class QuickSortMedian:
nums[i], nums[left] = nums[left], nums[i] nums[i], nums[left] = nums[left], nums[i]
return i # 返回基准数的索引 return i # 返回基准数的索引
def quick_sort(self, nums: list[int], left: int, right: int) -> None: def quick_sort(self, nums: list[int], left: int, right: int):
"""快速排序""" """快速排序"""
# 子数组长度为 1 时终止递归 # 子数组长度为 1 时终止递归
if left >= right: if left >= right:
@ -97,7 +97,7 @@ class QuickSortTailCall:
nums[i], nums[left] = nums[left], nums[i] nums[i], nums[left] = nums[left], nums[i]
return i # 返回基准数的索引 return i # 返回基准数的索引
def quick_sort(self, nums: list[int], left: int, right: int) -> None: def quick_sort(self, nums: list[int], left: int, right: int):
"""快速排序(尾递归优化)""" """快速排序(尾递归优化)"""
# 子数组长度为 1 时终止 # 子数组长度为 1 时终止
while left < right: while left < right:

@ -11,7 +11,7 @@ def digit(num: int, exp: int) -> int:
return (num // exp) % 10 return (num // exp) % 10
def counting_sort_digit(nums: list[int], exp: int) -> None: def counting_sort_digit(nums: list[int], exp: int):
"""计数排序(根据 nums 第 k 位排序)""" """计数排序(根据 nums 第 k 位排序)"""
# 十进制的位范围为 0~9 ,因此需要长度为 10 的桶 # 十进制的位范围为 0~9 ,因此需要长度为 10 的桶
counter = [0] * 10 counter = [0] * 10
@ -35,7 +35,7 @@ def counting_sort_digit(nums: list[int], exp: int) -> None:
nums[i] = res[i] nums[i] = res[i]
def radix_sort(nums: list[int]) -> None: def radix_sort(nums: list[int]):
"""基数排序""" """基数排序"""
# 获取数组的最大元素,用于判断最大位数 # 获取数组的最大元素,用于判断最大位数
m = max(nums) m = max(nums)

@ -8,7 +8,7 @@ Author: Krahets (krahets@163.com)
class ArrayDeque: class ArrayDeque:
"""基于环形数组实现的双向队列""" """基于环形数组实现的双向队列"""
def __init__(self, capacity: int) -> None: def __init__(self, capacity: int):
"""构造方法""" """构造方法"""
self.__nums: list[int] = [0] * capacity self.__nums: list[int] = [0] * capacity
self.__front: int = 0 self.__front: int = 0
@ -33,7 +33,7 @@ class ArrayDeque:
# 当 i 越过数组头部后,回到尾部 # 当 i 越过数组头部后,回到尾部
return (i + self.capacity()) % self.capacity() return (i + self.capacity()) % self.capacity()
def push_first(self, num: int) -> None: def push_first(self, num: int):
"""队首入队""" """队首入队"""
if self.__size == self.capacity(): if self.__size == self.capacity():
print("双向队列已满") print("双向队列已满")
@ -45,7 +45,7 @@ class ArrayDeque:
self.__nums[self.__front] = num self.__nums[self.__front] = num
self.__size += 1 self.__size += 1
def push_last(self, num: int) -> None: def push_last(self, num: int):
"""队尾入队""" """队尾入队"""
if self.__size == self.capacity(): if self.__size == self.capacity():
print("双向队列已满") print("双向队列已满")

@ -8,7 +8,7 @@ Author: Peng Chen (pengchzn@gmail.com)
class ArrayQueue: class ArrayQueue:
"""基于环形数组实现的队列""" """基于环形数组实现的队列"""
def __init__(self, size: int) -> None: def __init__(self, size: int):
"""构造方法""" """构造方法"""
self.__nums: list[int] = [0] * size # 用于存储队列元素的数组 self.__nums: list[int] = [0] * size # 用于存储队列元素的数组
self.__front: int = 0 # 队首指针,指向队首元素 self.__front: int = 0 # 队首指针,指向队首元素
@ -26,7 +26,7 @@ class ArrayQueue:
"""判断队列是否为空""" """判断队列是否为空"""
return self.__size == 0 return self.__size == 0
def push(self, num: int) -> None: def push(self, num: int):
"""入队""" """入队"""
if self.__size == self.capacity(): if self.__size == self.capacity():
raise IndexError("队列已满") raise IndexError("队列已满")

@ -8,7 +8,7 @@ Author: Peng Chen (pengchzn@gmail.com)
class ArrayStack: class ArrayStack:
"""基于数组实现的栈""" """基于数组实现的栈"""
def __init__(self) -> None: def __init__(self):
"""构造方法""" """构造方法"""
self.__stack: list[int] = [] self.__stack: list[int] = []
@ -20,7 +20,7 @@ class ArrayStack:
"""判断栈是否为空""" """判断栈是否为空"""
return self.__stack == [] return self.__stack == []
def push(self, item: int) -> None: def push(self, item: int):
"""入栈""" """入栈"""
self.__stack.append(item) self.__stack.append(item)

@ -8,7 +8,7 @@ Author: Krahets (krahets@163.com)
class ListNode: class ListNode:
"""双向链表节点""" """双向链表节点"""
def __init__(self, val: int) -> None: def __init__(self, val: int):
"""构造方法""" """构造方法"""
self.val: int = val self.val: int = val
self.next: ListNode | None = None # 后继节点引用(指针) self.next: ListNode | None = None # 后继节点引用(指针)
@ -18,7 +18,7 @@ class ListNode:
class LinkedListDeque: class LinkedListDeque:
"""基于双向链表实现的双向队列""" """基于双向链表实现的双向队列"""
def __init__(self) -> None: def __init__(self):
"""构造方法""" """构造方法"""
self.front: ListNode | None = None # 头节点 front self.front: ListNode | None = None # 头节点 front
self.rear: ListNode | None = None # 尾节点 rear self.rear: ListNode | None = None # 尾节点 rear
@ -32,7 +32,7 @@ class LinkedListDeque:
"""判断双向队列是否为空""" """判断双向队列是否为空"""
return self.size() == 0 return self.size() == 0
def push(self, num: int, is_front: bool) -> None: def push(self, num: int, is_front: bool):
"""入队操作""" """入队操作"""
node = ListNode(num) node = ListNode(num)
# 若链表为空,则令 front, rear 都指向 node # 若链表为空,则令 front, rear 都指向 node
@ -52,11 +52,11 @@ class LinkedListDeque:
self.rear = node # 更新尾节点 self.rear = node # 更新尾节点
self.__size += 1 # 更新队列长度 self.__size += 1 # 更新队列长度
def push_first(self, num: int) -> None: def push_first(self, num: int):
"""队首入队""" """队首入队"""
self.push(num, True) self.push(num, True)
def push_last(self, num: int) -> None: def push_last(self, num: int):
"""队尾入队""" """队尾入队"""
self.push(num, False) self.push(num, False)

@ -27,7 +27,7 @@ class LinkedListQueue:
"""判断队列是否为空""" """判断队列是否为空"""
return not self.__front return not self.__front
def push(self, num: int) -> None: def push(self, num: int):
"""入队""" """入队"""
# 尾节点后添加 num # 尾节点后添加 num
node = ListNode(num) node = ListNode(num)

@ -26,7 +26,7 @@ class LinkedListStack:
"""判断栈是否为空""" """判断栈是否为空"""
return not self.__peek return not self.__peek
def push(self, val: int) -> None: def push(self, val: int):
"""入栈""" """入栈"""
node = ListNode(val) node = ListNode(val)
node.next = self.__peek node.next = self.__peek

@ -88,7 +88,7 @@ class AVLTree:
# 平衡树,无需旋转,直接返回 # 平衡树,无需旋转,直接返回
return node return node
def insert(self, val) -> None: def insert(self, val):
"""插入节点""" """插入节点"""
self.root = self.__insert_helper(self.root, val) self.root = self.__insert_helper(self.root, val)
@ -109,7 +109,7 @@ class AVLTree:
# 2. 执行旋转操作,使该子树重新恢复平衡 # 2. 执行旋转操作,使该子树重新恢复平衡
return self.__rotate(node) return self.__rotate(node)
def remove(self, val: int) -> None: def remove(self, val: int):
"""删除节点""" """删除节点"""
self.root = self.__remove_helper(self.root, val) self.root = self.__remove_helper(self.root, val)

@ -13,7 +13,7 @@ from modules import *
class BinarySearchTree: class BinarySearchTree:
"""二叉搜索树""" """二叉搜索树"""
def __init__(self, nums: list[int]) -> None: def __init__(self, nums: list[int]):
"""构造方法""" """构造方法"""
nums.sort() nums.sort()
self.root = self.build_tree(nums, 0, len(nums) - 1) self.root = self.build_tree(nums, 0, len(nums) - 1)
@ -53,7 +53,7 @@ class BinarySearchTree:
break break
return cur return cur
def insert(self, num: int) -> None: def insert(self, num: int):
"""插入节点""" """插入节点"""
# 若树为空,直接提前返回 # 若树为空,直接提前返回
if self.root is None: if self.root is None:
@ -80,7 +80,7 @@ class BinarySearchTree:
else: else:
pre.left = node pre.left = node
def remove(self, num: int) -> None: def remove(self, num: int):
"""删除节点""" """删除节点"""
# 若树为空,直接提前返回 # 若树为空,直接提前返回
if self.root is None: if self.root is None:

@ -10,7 +10,7 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import * from modules import *
def pre_order(root: TreeNode | None) -> None: def pre_order(root: TreeNode | None):
"""前序遍历""" """前序遍历"""
if root is None: if root is None:
return return
@ -20,7 +20,7 @@ def pre_order(root: TreeNode | None) -> None:
pre_order(root=root.right) pre_order(root=root.right)
def in_order(root: TreeNode | None) -> None: def in_order(root: TreeNode | None):
"""中序遍历""" """中序遍历"""
if root is None: if root is None:
return return
@ -30,7 +30,7 @@ def in_order(root: TreeNode | None) -> None:
in_order(root=root.right) in_order(root=root.right)
def post_order(root: TreeNode | None) -> None: def post_order(root: TreeNode | None):
"""后序遍历""" """后序遍历"""
if root is None: if root is None:
return return

@ -8,7 +8,7 @@ from .tree_node import TreeNode, list_to_tree
from .list_node import ListNode, linked_list_to_list from .list_node import ListNode, linked_list_to_list
def print_matrix(mat: list[list[int]]) -> None: def print_matrix(mat: list[list[int]]):
"""Print a matrix""" """Print a matrix"""
s = [] s = []
for arr in mat: for arr in mat:
@ -16,19 +16,19 @@ def print_matrix(mat: list[list[int]]) -> None:
print("[\n" + ",\n".join(s) + "\n]") print("[\n" + ",\n".join(s) + "\n]")
def print_linked_list(head: ListNode | None) -> None: def print_linked_list(head: ListNode | None):
"""Print a linked list""" """Print a linked list"""
arr: list[int] = linked_list_to_list(head) arr: list[int] = linked_list_to_list(head)
print(" -> ".join([str(a) for a in arr])) print(" -> ".join([str(a) for a in arr]))
class Trunk: class Trunk:
def __init__(self, prev, string: str | None = None) -> None: def __init__(self, prev, string: str | None = None):
self.prev = prev self.prev = prev
self.str = string self.str = string
def show_trunks(p: Trunk | None) -> None: def show_trunks(p: Trunk | None):
if p is None: if p is None:
return return
show_trunks(p.prev) show_trunks(p.prev)
@ -37,7 +37,7 @@ def show_trunks(p: Trunk | None) -> None:
def print_tree( def print_tree(
root: TreeNode | None, prev: Trunk | None = None, is_left: bool = False root: TreeNode | None, prev: Trunk | None = None, is_left: bool = False
) -> None: ):
""" """
Print a binary tree Print a binary tree
This tree printer is borrowed from TECHIE DELIGHT This tree printer is borrowed from TECHIE DELIGHT
@ -67,13 +67,13 @@ def print_tree(
print_tree(root.left, trunk, False) print_tree(root.left, trunk, False)
def print_dict(mapp: dict) -> None: def print_dict(mapp: dict):
"""Print a dict""" """Print a dict"""
for key, value in mapp.items(): for key, value in mapp.items():
print(key, "->", value) print(key, "->", value)
def print_heap(heap: list[int]) -> None: def print_heap(heap: list[int]):
"""Print a heap both in array and tree representations""" """Print a heap both in array and tree representations"""
print("堆的数组表示:", heap) print("堆的数组表示:", heap)
print("堆的树状表示:") print("堆的树状表示:")

@ -6,7 +6,7 @@
class Vertex: class Vertex:
"""顶点类""" """顶点类"""
def __init__(self, val: int) -> None: def __init__(self, val: int):
self.val = val self.val = val

@ -314,7 +314,7 @@
=== "Python" === "Python"
```python title="" ```python title=""
def algorithm(n: int) -> None: def algorithm(n: int):
a = 0 # O(1) a = 0 # O(1)
b = [0] * 10000 # O(1) b = [0] * 10000 # O(1)
if n > 10: if n > 10:
@ -461,7 +461,7 @@
# do something # do something
return 0 return 0
def loop(n: int) -> None: def loop(n: int):
"""循环 O(1)""" """循环 O(1)"""
for _ in range(n): for _ in range(n):
function() function()

@ -48,7 +48,7 @@ $$
```python title="" ```python title=""
# 在某运行平台下 # 在某运行平台下
def algorithm(n: int) -> None: def algorithm(n: int):
a = 2 # 1 ns a = 2 # 1 ns
a = a + 1 # 1 ns a = a + 1 # 1 ns
a = a * 2 # 10 ns a = a * 2 # 10 ns
@ -226,14 +226,14 @@ $$
```python title="" ```python title=""
# 算法 A 时间复杂度:常数阶 # 算法 A 时间复杂度:常数阶
def algorithm_A(n: int) -> None: def algorithm_A(n: int):
print(0) print(0)
# 算法 B 时间复杂度:线性阶 # 算法 B 时间复杂度:线性阶
def algorithm_B(n: int) -> None: def algorithm_B(n: int):
for _ in range(n): for _ in range(n):
print(0) print(0)
# 算法 C 时间复杂度:常数阶 # 算法 C 时间复杂度:常数阶
def algorithm_C(n: int) -> None: def algorithm_C(n: int):
for _ in range(1000000): for _ in range(1000000):
print(0) print(0)
``` ```
@ -443,7 +443,7 @@ $$
=== "Python" === "Python"
```python title="" ```python title=""
def algorithm(n: int) -> None: def algorithm(n: int):
a = 1 # +1 a = 1 # +1
a = a + 1 # +1 a = a + 1 # +1
a = a * 2 # +1 a = a * 2 # +1
@ -644,7 +644,7 @@ $$
=== "Python" === "Python"
```python title="" ```python title=""
def algorithm(n: int) -> None: def algorithm(n: int):
a = 1 # +0技巧 1 a = 1 # +0技巧 1
a = a + n # +0技巧 1 a = a + n # +0技巧 1
# +n技巧 2 # +n技巧 2

Loading…
Cancel
Save