mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
feat: Revised the book (#978)
* Sync recent changes to the revised Word. * Revised the preface chapter * Revised the introduction chapter * Revised the computation complexity chapter * Revised the chapter data structure * Revised the chapter array and linked list * Revised the chapter stack and queue * Revised the chapter hashing * Revised the chapter tree * Revised the chapter heap * Revised the chapter graph * Revised the chapter searching * Reivised the sorting chapter * Revised the divide and conquer chapter * Revised the chapter backtacking * Revised the DP chapter * Revised the greedy chapter * Revised the appendix chapter * Revised the preface chapter doubly * Revised the figures
This commit is contained in:
@ -31,11 +31,11 @@ func insert(nums: inout [Int], num: Int, index: Int) {
|
||||
for i in nums.indices.dropFirst(index).reversed() {
|
||||
nums[i] = nums[i - 1]
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
// 将 num 赋给 index 处的元素
|
||||
nums[index] = num
|
||||
}
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
/* 删除索引 index 处的元素 */
|
||||
func remove(nums: inout [Int], index: Int) {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for i in nums.indices.dropFirst(index).dropLast() {
|
||||
|
||||
@ -62,7 +62,7 @@ enum LinkedList {
|
||||
let n2 = ListNode(x: 2)
|
||||
let n3 = ListNode(x: 5)
|
||||
let n4 = ListNode(x: 4)
|
||||
// 构建引用指向
|
||||
// 构建节点之间的引用
|
||||
n0.next = n1
|
||||
n1.next = n2
|
||||
n2.next = n3
|
||||
|
||||
@ -24,7 +24,7 @@ enum List {
|
||||
nums.removeAll()
|
||||
print("清空列表后 nums = \(nums)")
|
||||
|
||||
/* 尾部添加元素 */
|
||||
/* 在尾部添加元素 */
|
||||
nums.append(1)
|
||||
nums.append(3)
|
||||
nums.append(2)
|
||||
@ -32,7 +32,7 @@ enum List {
|
||||
nums.append(4)
|
||||
print("添加元素后 nums = \(nums)")
|
||||
|
||||
/* 中间插入元素 */
|
||||
/* 在中间插入元素 */
|
||||
nums.insert(6, at: 3)
|
||||
print("在索引 3 处插入数字 6 ,得到 nums = \(nums)")
|
||||
|
||||
|
||||
@ -4,11 +4,11 @@
|
||||
* Author: nuomi1 (nuomi1@qq.com)
|
||||
*/
|
||||
|
||||
/* 列表类简易实现 */
|
||||
/* 列表类 */
|
||||
class MyList {
|
||||
private var arr: [Int] // 数组(存储列表元素)
|
||||
private var _capacity = 10 // 列表容量
|
||||
private var _size = 0 // 列表长度(即当前元素数量)
|
||||
private var _size = 0 // 列表长度(当前元素数量)
|
||||
private let extendRatio = 2 // 每次列表扩容的倍数
|
||||
|
||||
/* 构造方法 */
|
||||
@ -16,7 +16,7 @@ class MyList {
|
||||
arr = Array(repeating: 0, count: _capacity)
|
||||
}
|
||||
|
||||
/* 获取列表长度(即当前元素数量)*/
|
||||
/* 获取列表长度(当前元素数量)*/
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
@ -43,7 +43,7 @@ class MyList {
|
||||
arr[index] = num
|
||||
}
|
||||
|
||||
/* 尾部添加元素 */
|
||||
/* 在尾部添加元素 */
|
||||
func add(num: Int) {
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if _size == _capacity {
|
||||
@ -54,7 +54,7 @@ class MyList {
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* 中间插入元素 */
|
||||
/* 在中间插入元素 */
|
||||
func insert(index: Int, num: Int) {
|
||||
if index < 0 || index >= _size {
|
||||
fatalError("索引越界")
|
||||
@ -113,7 +113,7 @@ enum _MyList {
|
||||
static func main() {
|
||||
/* 初始化列表 */
|
||||
let nums = MyList()
|
||||
/* 尾部添加元素 */
|
||||
/* 在尾部添加元素 */
|
||||
nums.add(num: 1)
|
||||
nums.add(num: 3)
|
||||
nums.add(num: 2)
|
||||
@ -121,7 +121,7 @@ enum _MyList {
|
||||
nums.add(num: 4)
|
||||
print("列表 nums = \(nums.toArray()) ,容量 = \(nums.capacity()) ,长度 = \(nums.size())")
|
||||
|
||||
/* 中间插入元素 */
|
||||
/* 在中间插入元素 */
|
||||
nums.insert(index: 3, num: 6)
|
||||
print("在索引 3 处插入数字 6 ,得到 nums = \(nums.toArray())")
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]
|
||||
// 计算该格子对应的主对角线和副对角线
|
||||
let diag1 = row - col + n - 1
|
||||
let diag2 = row + col
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线存在皇后
|
||||
// 剪枝:不允许该格子所在列、主对角线、副对角线上存在皇后
|
||||
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
|
||||
// 尝试:将皇后放置在该格子
|
||||
state[row][col] = "Q"
|
||||
@ -39,8 +39,8 @@ func nQueens(n: Int) -> [[[String]]] {
|
||||
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
|
||||
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
|
||||
var cols = Array(repeating: false, count: n) // 记录列是否有皇后
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // 记录主对角线是否有皇后
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // 记录副对角线是否有皇后
|
||||
var diags1 = Array(repeating: false, count: 2 * n - 1) // 记录主对角线上是否有皇后
|
||||
var diags2 = Array(repeating: false, count: 2 * n - 1) // 记录副对角线上是否有皇后
|
||||
var res: [[[String]]] = []
|
||||
|
||||
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
|
||||
|
||||
@ -30,7 +30,7 @@ func whileLoop(n: Int) -> Int {
|
||||
func whileLoopII(n: Int) -> Int {
|
||||
var res = 0
|
||||
var i = 1 // 初始化条件变量
|
||||
// 循环求和 1, 4, ...
|
||||
// 循环求和 1, 4, 10, ...
|
||||
while i <= n {
|
||||
res += i
|
||||
// 更新条件变量
|
||||
|
||||
@ -12,7 +12,7 @@ func move(src: inout [Int], tar: inout [Int]) {
|
||||
tar.append(pan)
|
||||
}
|
||||
|
||||
/* 求解汉诺塔:问题 f(i) */
|
||||
/* 求解汉诺塔问题 f(i) */
|
||||
func dfs(i: Int, src: inout [Int], buf: inout [Int], tar: inout [Int]) {
|
||||
// 若 src 只剩下一个圆盘,则直接将其移到 tar
|
||||
if i == 1 {
|
||||
@ -27,7 +27,7 @@ func dfs(i: Int, src: inout [Int], buf: inout [Int], tar: inout [Int]) {
|
||||
dfs(i: i - 1, src: &buf, buf: &src, tar: &tar)
|
||||
}
|
||||
|
||||
/* 求解汉诺塔 */
|
||||
/* 求解汉诺塔问题 */
|
||||
func solveHanota(A: inout [Int], B: inout [Int], C: inout [Int]) {
|
||||
let n = A.count
|
||||
// 列表尾部是柱子顶部
|
||||
|
||||
@ -22,7 +22,7 @@ func backtrack(choices: [Int], state: Int, n: Int, res: inout [Int]) {
|
||||
|
||||
/* 爬楼梯:回溯 */
|
||||
func climbingStairsBacktrack(n: Int) -> Int {
|
||||
let choices = [1, 2] // 可选择向上爬 1 或 2 阶
|
||||
let choices = [1, 2] // 可选择向上爬 1 阶或 2 阶
|
||||
let state = 0 // 从第 0 阶开始爬
|
||||
var res: [Int] = []
|
||||
res.append(0) // 使用 res[0] 记录方案数量
|
||||
|
||||
@ -14,7 +14,7 @@ func coinChangeDP(coins: [Int], amt: Int) -> Int {
|
||||
for a in stride(from: 1, through: amt, by: 1) {
|
||||
dp[0][a] = MAX
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
// 状态转移:其余行和列
|
||||
for i in stride(from: 1, through: n, by: 1) {
|
||||
for a in stride(from: 1, through: amt, by: 1) {
|
||||
if coins[i - 1] > a {
|
||||
|
||||
@ -73,7 +73,7 @@ func editDistanceDP(s: String, t: String) -> Int {
|
||||
for j in stride(from: 1, through: m, by: 1) {
|
||||
dp[0][j] = j
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
// 状态转移:其余行和列
|
||||
for i in stride(from: 1, through: n, by: 1) {
|
||||
for j in stride(from: 1, through: m, by: 1) {
|
||||
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
|
||||
|
||||
@ -6,11 +6,11 @@
|
||||
|
||||
/* 0-1 背包:暴力搜索 */
|
||||
func knapsackDFS(wgt: [Int], val: [Int], i: Int, c: Int) -> Int {
|
||||
// 若已选完所有物品或背包无容量,则返回价值 0
|
||||
// 若已选完所有物品或背包无剩余容量,则返回价值 0
|
||||
if i == 0 || c == 0 {
|
||||
return 0
|
||||
}
|
||||
// 若超过背包容量,则只能不放入背包
|
||||
// 若超过背包容量,则只能选择不放入背包
|
||||
if wgt[i - 1] > c {
|
||||
return knapsackDFS(wgt: wgt, val: val, i: i - 1, c: c)
|
||||
}
|
||||
@ -23,7 +23,7 @@ func knapsackDFS(wgt: [Int], val: [Int], i: Int, c: Int) -> Int {
|
||||
|
||||
/* 0-1 背包:记忆化搜索 */
|
||||
func knapsackDFSMem(wgt: [Int], val: [Int], mem: inout [[Int]], i: Int, c: Int) -> Int {
|
||||
// 若已选完所有物品或背包无容量,则返回价值 0
|
||||
// 若已选完所有物品或背包无剩余容量,则返回价值 0
|
||||
if i == 0 || c == 0 {
|
||||
return 0
|
||||
}
|
||||
@ -31,7 +31,7 @@ func knapsackDFSMem(wgt: [Int], val: [Int], mem: inout [[Int]], i: Int, c: Int)
|
||||
if mem[i][c] != -1 {
|
||||
return mem[i][c]
|
||||
}
|
||||
// 若超过背包容量,则只能不放入背包
|
||||
// 若超过背包容量,则只能选择不放入背包
|
||||
if wgt[i - 1] > c {
|
||||
return knapsackDFSMem(wgt: wgt, val: val, mem: &mem, i: i - 1, c: c)
|
||||
}
|
||||
|
||||
@ -58,7 +58,7 @@ func minPathSumDP(grid: [[Int]]) -> Int {
|
||||
for i in stride(from: 1, to: n, by: 1) {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0]
|
||||
}
|
||||
// 状态转移:其余行列
|
||||
// 状态转移:其余行和列
|
||||
for i in stride(from: 1, to: n, by: 1) {
|
||||
for j in stride(from: 1, to: m, by: 1) {
|
||||
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
|
||||
|
||||
@ -8,7 +8,7 @@ import utils
|
||||
|
||||
/* 基于邻接表实现的无向图类 */
|
||||
public class GraphAdjList {
|
||||
// 邻接表,key: 顶点,value:该顶点的所有邻接顶点
|
||||
// 邻接表,key:顶点,value:该顶点的所有邻接顶点
|
||||
public private(set) var adjList: [Vertex: [Vertex]]
|
||||
|
||||
/* 构造方法 */
|
||||
|
||||
@ -67,7 +67,7 @@ class GraphAdjMat {
|
||||
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
|
||||
fatalError("越界")
|
||||
}
|
||||
// 在无向图中,邻接矩阵沿主对角线对称,即满足 (i, j) == (j, i)
|
||||
// 在无向图中,邻接矩阵关于主对角线对称,即满足 (i, j) == (j, i)
|
||||
adjMat[i][j] = 1
|
||||
adjMat[j][i] = 1
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ func graphBFS(graph: GraphAdjList, startVet: Vertex) -> [Vertex] {
|
||||
// 遍历该顶点的所有邻接顶点
|
||||
for adjVet in graph.adjList[vet] ?? [] {
|
||||
if visited.contains(adjVet) {
|
||||
continue // 跳过已被访问过的顶点
|
||||
continue // 跳过已被访问的顶点
|
||||
}
|
||||
que.append(adjVet) // 只入队未访问的顶点
|
||||
visited.insert(adjVet) // 标记该顶点已被访问
|
||||
|
||||
@ -14,7 +14,7 @@ func dfs(graph: GraphAdjList, visited: inout Set<Vertex>, res: inout [Vertex], v
|
||||
// 遍历该顶点的所有邻接顶点
|
||||
for adjVet in graph.adjList[vet] ?? [] {
|
||||
if visited.contains(adjVet) {
|
||||
continue // 跳过已被访问过的顶点
|
||||
continue // 跳过已被访问的顶点
|
||||
}
|
||||
// 递归访问邻接顶点
|
||||
dfs(graph: graph, visited: &visited, res: &res, vet: adjVet)
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
|
||||
import utils
|
||||
|
||||
/* 基于数组简易实现的哈希表 */
|
||||
/* 基于数组实现的哈希表 */
|
||||
class ArrayHashMap {
|
||||
private var buckets: [Pair?] = []
|
||||
|
||||
|
||||
@ -86,7 +86,7 @@ class MaxHeap {
|
||||
if isEmpty() {
|
||||
fatalError("堆为空")
|
||||
}
|
||||
// 交换根节点与最右叶节点(即交换首元素与尾元素)
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
swap(i: 0, j: size() - 1)
|
||||
// 删除节点
|
||||
let val = maxHeap.remove(at: size() - 1)
|
||||
|
||||
@ -24,9 +24,9 @@ func binarySearch(nums: [Int], target: Int) -> Int {
|
||||
return -1
|
||||
}
|
||||
|
||||
/* 二分查找(左闭右开) */
|
||||
/* 二分查找(左闭右开区间) */
|
||||
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
|
||||
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
// 初始化左闭右开区间 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
var i = 0
|
||||
var j = nums.count
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
@ -55,7 +55,7 @@ enum BinarySearch {
|
||||
var index = binarySearch(nums: nums, target: target)
|
||||
print("目标元素 6 的索引 = \(index)")
|
||||
|
||||
/* 二分查找(左闭右开) */
|
||||
/* 二分查找(左闭右开区间) */
|
||||
index = binarySearchLCRO(nums: nums, target: target)
|
||||
print("目标元素 6 的索引 = \(index)")
|
||||
}
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
|
||||
/* 方法一:暴力枚举 */
|
||||
func twoSumBruteForce(nums: [Int], target: Int) -> [Int] {
|
||||
// 两层循环,时间复杂度 O(n^2)
|
||||
// 两层循环,时间复杂度为 O(n^2)
|
||||
for i in nums.indices.dropLast() {
|
||||
for j in nums.indices.dropFirst(i + 1) {
|
||||
if nums[i] + nums[j] == target {
|
||||
@ -19,9 +19,9 @@ func twoSumBruteForce(nums: [Int], target: Int) -> [Int] {
|
||||
|
||||
/* 方法二:辅助哈希表 */
|
||||
func twoSumHashTable(nums: [Int], target: Int) -> [Int] {
|
||||
// 辅助哈希表,空间复杂度 O(n)
|
||||
// 辅助哈希表,空间复杂度为 O(n)
|
||||
var dic: [Int: Int] = [:]
|
||||
// 单层循环,时间复杂度 O(n)
|
||||
// 单层循环,时间复杂度为 O(n)
|
||||
for i in nums.indices {
|
||||
if let j = dic[target - nums[i]] {
|
||||
return [j, i]
|
||||
|
||||
@ -11,7 +11,7 @@ func bucketSort(nums: inout [Double]) {
|
||||
var buckets = (0 ..< k).map { _ in [Double]() }
|
||||
// 1. 将数组元素分配到各个桶中
|
||||
for num in nums {
|
||||
// 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
|
||||
// 输入数据范围为 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
|
||||
let i = Int(num * Double(k))
|
||||
// 将 num 添加进桶 i
|
||||
buckets[i].append(num)
|
||||
|
||||
@ -37,7 +37,7 @@ func heapSort(nums: inout [Int]) {
|
||||
}
|
||||
// 从堆中提取最大元素,循环 n-1 轮
|
||||
for i in stride(from: nums.count - 1, to: 0, by: -1) {
|
||||
// 交换根节点与最右叶节点(即交换首元素与尾元素)
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
nums.swapAt(0, i)
|
||||
// 以根节点为起点,从顶至底进行堆化
|
||||
siftDown(nums: &nums, n: i, i: 0)
|
||||
|
||||
@ -14,7 +14,7 @@ func swap(nums: inout [Int], i: Int, j: Int) {
|
||||
/* 快速排序类 */
|
||||
/* 哨兵划分 */
|
||||
func partition(nums: inout [Int], left: Int, right: Int) -> Int {
|
||||
// 以 nums[left] 作为基准数
|
||||
// 以 nums[left] 为基准数
|
||||
var i = left
|
||||
var j = right
|
||||
while i < j {
|
||||
@ -87,7 +87,7 @@ func quickSortTailCall(nums: inout [Int], left: Int, right: Int) {
|
||||
while left < right {
|
||||
// 哨兵划分操作
|
||||
let pivot = partition(nums: &nums, left: left, right: right)
|
||||
// 对两个子数组中较短的那个执行快排
|
||||
// 对两个子数组中较短的那个执行快速排序
|
||||
if (pivot - left) < (right - pivot) {
|
||||
quickSortTailCall(nums: &nums, left: left, right: pivot - 1) // 递归排序左子数组
|
||||
left = pivot + 1 // 剩余未排序区间为 [pivot + 1, right]
|
||||
|
||||
@ -12,7 +12,7 @@ func digit(num: Int, exp: Int) -> Int {
|
||||
|
||||
/* 计数排序(根据 nums 第 k 位排序) */
|
||||
func countingSortDigit(nums: inout [Int], exp: Int) {
|
||||
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶
|
||||
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶数组
|
||||
var counter = Array(repeating: 0, count: 10)
|
||||
let n = nums.count
|
||||
// 统计 0~9 各数字的出现次数
|
||||
|
||||
@ -38,7 +38,7 @@ class LinkedListDeque {
|
||||
/* 入队操作 */
|
||||
private func push(num: Int, isFront: Bool) {
|
||||
let node = ListNode(val: num)
|
||||
// 若链表为空,则令 front, rear 都指向 node
|
||||
// 若链表为空,则令 front 和 rear 都指向 node
|
||||
if isEmpty() {
|
||||
front = node
|
||||
rear = node
|
||||
|
||||
@ -17,7 +17,7 @@ enum BinaryTree {
|
||||
let n3 = TreeNode(x: 3)
|
||||
let n4 = TreeNode(x: 4)
|
||||
let n5 = TreeNode(x: 5)
|
||||
// 构建引用指向(即指针)
|
||||
// 构建节点之间的引用(指针)
|
||||
n1.left = n2
|
||||
n1.right = n3
|
||||
n2.left = n4
|
||||
|
||||
Reference in New Issue
Block a user