krahets 7 months ago
parent aea68142f8
commit d8caf02e9e

@ -709,8 +709,8 @@ comments: true
### 删除索引 index 处的元素 ###
def remove(nums, index)
# 把索引 index 之后的所有元素向前移动一位
for i in index...nums.length
nums[i] = nums[i + 1] || 0
for i in index...(nums.length - 1)
nums[i] = nums[i + 1]
end
end
```
@ -949,7 +949,7 @@ comments: true
count += nums[i]
}
// 直接遍历数组元素
for (j: Int in nums) {
for (j in nums) {
count += j
}
}
@ -1155,7 +1155,8 @@ comments: true
/* 在数组中查找指定元素 */
fun find(nums: IntArray, target: Int): Int {
for (i in nums.indices) {
if (nums[i] == target) return i
if (nums[i] == target)
return i
}
return -1
}

@ -597,7 +597,7 @@ comments: true
=== "Kotlin"
```kotlin title="linked_list.kt"
/* 在链表的节点 n0 之后插入节点p */
/* 在链表的节点 n0 之后插入节点 P */
fun insert(n0: ListNode?, p: ListNode?) {
val n1 = n0?.next
p?.next = n1
@ -811,9 +811,11 @@ comments: true
```kotlin title="linked_list.kt"
/* 删除链表的节点 n0 之后的首个节点 */
fun remove(n0: ListNode?) {
val p = n0?.next
if (n0?.next == null)
return
val p = n0.next
val n1 = p?.next
n0?.next = n1
n0.next = n1
}
```
@ -1018,7 +1020,9 @@ comments: true
fun access(head: ListNode?, index: Int): ListNode? {
var h = head
for (i in 0..<index) {
h = h?.next
if (h == null)
return null
h = h.next
}
return h
}
@ -1249,7 +1253,8 @@ comments: true
var index = 0
var h = head
while (h != null) {
if (h.value == target) return index
if (h.value == target)
return index
h = h.next
index++
}

@ -2181,11 +2181,11 @@ comments: true
/* 列表类 */
class MyList {
private var arr: IntArray = intArrayOf() // 数组(存储列表元素)
private var capacity = 10 // 列表容量
private var size = 0 // 列表长度(当前元素数量)
private var extendRatio = 2 // 每次列表扩容的倍数
private var capacity: Int = 10 // 列表容量
private var size: Int = 0 // 列表长度(当前元素数量)
private var extendRatio: Int = 2 // 每次列表扩容的倍数
/* 构造函数 */
/* 构造方法 */
init {
arr = IntArray(capacity)
}
@ -2204,7 +2204,7 @@ comments: true
fun get(index: Int): Int {
// 索引如果越界,则抛出异常,下同
if (index < 0 || index >= size)
throw IndexOutOfBoundsException()
throw IndexOutOfBoundsException("索引越界")
return arr[index]
}
@ -2244,7 +2244,7 @@ comments: true
fun remove(index: Int): Int {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
val num: Int = arr[index]
val num = arr[index]
// 将将索引 index 之后的元素都向前移动一位
for (j in index..<size - 1)
arr[j] = arr[j + 1]

@ -510,7 +510,7 @@ comments: true
path!!.add(root)
if (root.value == 7) {
// 记录解
res!!.add(ArrayList(path!!))
res!!.add(path!!.toMutableList())
}
preOrder(root.left)
preOrder(root.right)
@ -854,7 +854,7 @@ comments: true
path!!.add(root)
if (root.value == 7) {
// 记录解
res!!.add(ArrayList(path!!))
res!!.add(path!!.toMutableList())
}
preOrder(root.left)
preOrder(root.right)
@ -1790,17 +1790,17 @@ comments: true
```kotlin title="preorder_traversal_iii_template.kt"
/* 判断当前状态是否为解 */
fun isSolution(state: List<TreeNode?>): Boolean {
fun isSolution(state: MutableList<TreeNode?>): Boolean {
return state.isNotEmpty() && state[state.size - 1]?.value == 7
}
/* 记录解 */
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<List<TreeNode?>?>) {
res.add(state?.let { ArrayList(it) })
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<MutableList<TreeNode?>?>) {
res.add(state!!.toMutableList())
}
/* 判断在当前状态下,该选择是否合法 */
fun isValid(state: List<TreeNode?>?, choice: TreeNode?): Boolean {
fun isValid(state: MutableList<TreeNode?>?, choice: TreeNode?): Boolean {
return choice != null && choice.value != 3
}
@ -1817,8 +1817,8 @@ comments: true
/* 回溯算法:例题三 */
fun backtrack(
state: MutableList<TreeNode?>,
choices: List<TreeNode?>,
res: MutableList<List<TreeNode?>?>
choices: MutableList<TreeNode?>,
res: MutableList<MutableList<TreeNode?>?>
) {
// 检查是否为解
if (isSolution(state)) {
@ -1832,7 +1832,7 @@ comments: true
// 尝试:做出选择,更新状态
makeChoice(state, choice)
// 进行下一轮选择
backtrack(state, listOf(choice!!.left, choice.right), res)
backtrack(state, mutableListOf(choice!!.left, choice.right), res)
// 回退:撤销选择,恢复到之前的状态
undoChoice(state, choice)
}

@ -646,17 +646,17 @@ comments: true
fun backtrack(
row: Int,
n: Int,
state: List<MutableList<String>>,
res: MutableList<List<List<String>>?>,
state: MutableList<MutableList<String>>,
res: MutableList<MutableList<MutableList<String>>?>,
cols: BooleanArray,
diags1: BooleanArray,
diags2: BooleanArray
) {
// 当放置完所有行时,记录解
if (row == n) {
val copyState: MutableList<List<String>> = ArrayList()
val copyState = mutableListOf<MutableList<String>>()
for (sRow in state) {
copyState.add(ArrayList(sRow))
copyState.add(sRow.toMutableList())
}
res.add(copyState)
return
@ -685,11 +685,11 @@ comments: true
}
/* 求解 n 皇后 */
fun nQueens(n: Int): List<List<List<String>>?> {
fun nQueens(n: Int): MutableList<MutableList<MutableList<String>>?> {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
val state: MutableList<MutableList<String>> = ArrayList()
val state = mutableListOf<MutableList<String>>()
for (i in 0..<n) {
val row: MutableList<String> = ArrayList()
val row = mutableListOf<String>()
for (j in 0..<n) {
row.add("#")
}
@ -698,7 +698,7 @@ comments: true
val cols = BooleanArray(n) // 记录列是否有皇后
val diags1 = BooleanArray(2 * n - 1) // 记录主对角线上是否有皇后
val diags2 = BooleanArray(2 * n - 1) // 记录次对角线上是否有皇后
val res: MutableList<List<List<String>>?> = ArrayList()
val res = mutableListOf<MutableList<MutableList<String>>?>()
backtrack(0, n, state, res, cols, diags1, diags2)

@ -471,11 +471,11 @@ comments: true
state: MutableList<Int>,
choices: IntArray,
selected: BooleanArray,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 当状态长度等于元素数量时,记录解
if (state.size == choices.size) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -496,9 +496,9 @@ comments: true
}
/* 全排列 I */
fun permutationsI(nums: IntArray): List<List<Int>?> {
val res: MutableList<List<Int>?> = ArrayList()
backtrack(ArrayList(), nums, BooleanArray(nums.size), res)
fun permutationsI(nums: IntArray): MutableList<MutableList<Int>?> {
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
return res
}
```
@ -999,11 +999,11 @@ comments: true
) {
// 当状态长度等于元素数量时,记录解
if (state.size == choices.size) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
val duplicated: MutableSet<Int> = HashSet()
val duplicated = HashSet<Int>()
for (i in choices.indices) {
val choice = choices[i]
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
@ -1023,8 +1023,8 @@ comments: true
/* 全排列 II */
fun permutationsII(nums: IntArray): MutableList<MutableList<Int>?> {
val res: MutableList<MutableList<Int>?> = ArrayList()
backtrack(ArrayList(), nums, BooleanArray(nums.size), res)
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
return res
}
```

@ -435,11 +435,11 @@ comments: true
target: Int,
total: Int,
choices: IntArray,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 子集和等于 target 时,记录解
if (total == target) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -458,10 +458,10 @@ comments: true
}
/* 求解子集和 I包含重复子集 */
fun subsetSumINaive(nums: IntArray, target: Int): List<List<Int>?> {
val state: MutableList<Int> = ArrayList() // 状态(子集)
fun subsetSumINaive(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // 状态(子集)
val total = 0 // 子集和
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
backtrack(state, target, total, nums, res)
return res
}
@ -973,11 +973,11 @@ comments: true
target: Int,
choices: IntArray,
start: Int,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 子集和等于 target 时,记录解
if (target == 0) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -998,11 +998,11 @@ comments: true
}
/* 求解子集和 I */
fun subsetSumI(nums: IntArray, target: Int): List<List<Int>?> {
val state: MutableList<Int> = ArrayList() // 状态(子集)
Arrays.sort(nums) // 对 nums 进行排序
fun subsetSumI(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // 状态(子集)
nums.sort() // 对 nums 进行排序
val start = 0 // 遍历起始点
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
backtrack(state, target, nums, start, res)
return res
}
@ -1555,11 +1555,11 @@ comments: true
target: Int,
choices: IntArray,
start: Int,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 子集和等于 target 时,记录解
if (target == 0) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -1585,11 +1585,11 @@ comments: true
}
/* 求解子集和 II */
fun subsetSumII(nums: IntArray, target: Int): List<List<Int>?> {
val state: MutableList<Int> = ArrayList() // 状态(子集)
Arrays.sort(nums) // 对 nums 进行排序
fun subsetSumII(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // 状态(子集)
nums.sort() // 对 nums 进行排序
val start = 0 // 遍历起始点
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
backtrack(state, target, nums, start, res)
return res
}

@ -1915,9 +1915,9 @@ $$
/* 平方阶 */
fun quadratic(n: Int) {
// 矩阵占用 O(n^2) 空间
val numMatrix: Array<Array<Int>?> = arrayOfNulls(n)
val numMatrix = arrayOfNulls<Array<Int>?>(n)
// 二维列表占用 O(n^2) 空间
val numList: MutableList<MutableList<Int>> = arrayListOf()
val numList = mutableListOf<MutableList<Int>>()
for (i in 0..<n) {
val tmp = mutableListOf<Int>()
for (j in 0..<n) {

@ -195,11 +195,11 @@ comments: true
```ruby title=""
# 在某运行平台下
def algorithm(n)
a = 2 # 1 ns
a = 2 # 1 ns
a = a + 1 # 1 ns
a = a * 2 # 10 ns
# 循环 n 次
(n...0).each do # 1 ns
(0...n).each do # 1 ns
puts 0 # 5 ns
end
end
@ -520,7 +520,7 @@ $$
// 算法 C 的时间复杂度:常数阶
fn algorithm_C(n: i32) void {
_ = n;
for (0..1000000) |_| {
for (0..1000000) |_| {
std.debug.print("{}\n", .{0});
}
}
@ -696,7 +696,7 @@ $$
for (int i = 0; i < n; i++) { // +1 i ++
printf("%d", 0); // +1
}
}
}
```
=== "Kotlin"
@ -1029,13 +1029,13 @@ $T(n)$ 是一次函数,说明其运行时间的增长趋势是线性的,因
// +n技巧 2
for(0..(5 * n + 1)) |_| {
std.debug.print("{}\n", .{0});
std.debug.print("{}\n", .{0});
}
// +n*n技巧 3
for(0..(2 * n)) |_| {
for(0..(n + 1)) |_| {
std.debug.print("{}\n", .{0});
std.debug.print("{}\n", .{0});
}
}
}
@ -1245,7 +1245,7 @@ $$
/* 常数阶 */
fun constant(n: Int): Int {
var count = 0
val size = 10_0000
val size = 100000
for (i in 0..<size)
count++
return count
@ -2168,7 +2168,7 @@ $$
```kotlin title="time_complexity.kt"
/* 平方阶(冒泡排序) */
fun bubbleSort(nums: IntArray): Int {
var count = 0
var count = 0 // 计数器
// 外循环:未排序区间为 [0, i]
for (i in nums.size - 1 downTo 1) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
@ -3231,7 +3231,7 @@ $$
if (n <= 1)
return 1
var count = linearLogRecur(n / 2) + linearLogRecur(n / 2)
for (i in 0..<n.toInt()) {
for (i in 0..<n) {
count++
}
return count
@ -3859,10 +3859,9 @@ $$
for (i in 0..<n) {
nums[i] = i + 1
}
// 随机打乱数组元素
val mutableList = nums.toMutableList()
// 随机打乱数组元素
mutableList.shuffle()
// Integer[] -> int[]
val res = arrayOfNulls<Int>(n)
for (i in 0..<n) {
res[i] = mutableList[i]

@ -174,13 +174,14 @@ comments: true
=== "Ruby"
```ruby title=""
# Ruby 的列表可以自由存储各种基本数据类型和对象引用
data = [0, 0.0, 'a', false, ListNode(0)]
```
=== "Zig"
```zig title=""
```
??? pythontutor "可视化运行"

@ -143,7 +143,7 @@ $$
**尽管浮点数 `float` 扩展了取值范围,但其副作用是牺牲了精度**。整数类型 `int` 将全部 32 比特用于表示数字,数字是均匀分布的;而由于指数位的存在,浮点数 `float` 的数值越大,相邻两个数字之间的差值就会趋向越大。
如表 3-2 所示,指数位 $E = 0$ 和 $E = 255$ 具有特殊含义,**用于表示零、无穷大、$\mathrm{NaN}$ 等**。
如表 3-2 所示,指数位 $\mathrm{E} = 0$ 和 $\mathrm{E} = 255$ 具有特殊含义,**用于表示零、无穷大、$\mathrm{NaN}$ 等**。
<p align="center"> 表 3-2 &nbsp; 指数位含义 </p>

@ -2824,6 +2824,9 @@ comments: true
free(pair);
}
}
free(hashMap->buckets);
free(hashMap->TOMBSTONE);
free(hashMap);
}
/* 哈希函数 */

@ -1826,8 +1826,8 @@ comments: true
if (fNext) {
fNext->prev = NULL;
deque->front->next = NULL;
delDoublyListNode(deque->front);
}
delDoublyListNode(deque->front);
deque->front = fNext; // 更新头节点
}
// 队尾出队操作
@ -1837,8 +1837,8 @@ comments: true
if (rPrev) {
rPrev->next = NULL;
deque->rear->prev = NULL;
delDoublyListNode(deque->rear);
}
delDoublyListNode(deque->rear);
deque->rear = rPrev; // 更新尾节点
}
deque->queSize--; // 更新队列长度

@ -694,8 +694,8 @@ Please note that after deletion, the former last element becomes "meaningless,"
### 删除索引 index 处的元素 ###
def remove(nums, index)
# 把索引 index 之后的所有元素向前移动一位
for i in index...nums.length
nums[i] = nums[i + 1] || 0
for i in index...(nums.length - 1)
nums[i] = nums[i + 1]
end
end
```
@ -934,7 +934,7 @@ In most programming languages, we can traverse an array either by using indices
count += nums[i]
}
// 直接遍历数组元素
for (j: Int in nums) {
for (j in nums) {
count += j
}
}
@ -1140,7 +1140,8 @@ Because arrays are linear data structures, this operation is commonly referred t
/* 在数组中查找指定元素 */
fun find(nums: IntArray, target: Int): Int {
for (i in nums.indices) {
if (nums[i] == target) return i
if (nums[i] == target)
return i
}
return -1
}

@ -544,7 +544,7 @@ By comparison, inserting an element into an array has a time complexity of $O(n)
=== "Kotlin"
```kotlin title="linked_list.kt"
/* 在链表的节点 n0 之后插入节点p */
/* 在链表的节点 n0 之后插入节点 P */
fun insert(n0: ListNode?, p: ListNode?) {
val n1 = n0?.next
p?.next = n1
@ -758,9 +758,11 @@ It's important to note that even though node `P` continues to point to `n1` afte
```kotlin title="linked_list.kt"
/* 删除链表的节点 n0 之后的首个节点 */
fun remove(n0: ListNode?) {
val p = n0?.next
if (n0?.next == null)
return
val p = n0.next
val n1 = p?.next
n0?.next = n1
n0.next = n1
}
```
@ -965,7 +967,9 @@ It's important to note that even though node `P` continues to point to `n1` afte
fun access(head: ListNode?, index: Int): ListNode? {
var h = head
for (i in 0..<index) {
h = h?.next
if (h == null)
return null
h = h.next
}
return h
}
@ -1196,7 +1200,8 @@ Traverse the linked list to locate a node whose value matches `target`, and then
var index = 0
var h = head
while (h != null) {
if (h.value == target) return index
if (h.value == target)
return index
h = h.next
index++
}

@ -2047,11 +2047,11 @@ To enhance our understanding of how lists work, we will attempt to implement a s
/* 列表类 */
class MyList {
private var arr: IntArray = intArrayOf() // 数组(存储列表元素)
private var capacity = 10 // 列表容量
private var size = 0 // 列表长度(当前元素数量)
private var extendRatio = 2 // 每次列表扩容的倍数
private var capacity: Int = 10 // 列表容量
private var size: Int = 0 // 列表长度(当前元素数量)
private var extendRatio: Int = 2 // 每次列表扩容的倍数
/* 构造函数 */
/* 构造方法 */
init {
arr = IntArray(capacity)
}
@ -2070,7 +2070,7 @@ To enhance our understanding of how lists work, we will attempt to implement a s
fun get(index: Int): Int {
// 索引如果越界,则抛出异常,下同
if (index < 0 || index >= size)
throw IndexOutOfBoundsException()
throw IndexOutOfBoundsException("索引越界")
return arr[index]
}
@ -2110,7 +2110,7 @@ To enhance our understanding of how lists work, we will attempt to implement a s
fun remove(index: Int): Int {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
val num: Int = arr[index]
val num = arr[index]
// 将将索引 index 之后的元素都向前移动一位
for (j in index..<size - 1)
arr[j] = arr[j + 1]

@ -1820,9 +1820,9 @@ Quadratic order is common in matrices and graphs, where the number of elements i
/* 平方阶 */
fun quadratic(n: Int) {
// 矩阵占用 O(n^2) 空间
val numMatrix: Array<Array<Int>?> = arrayOfNulls(n)
val numMatrix = arrayOfNulls<Array<Int>?>(n)
// 二维列表占用 O(n^2) 空间
val numList: MutableList<MutableList<Int>> = arrayListOf()
val numList = mutableListOf<MutableList<Int>>()
for (i in 0..<n) {
val tmp = mutableListOf<Int>()
for (j in 0..<n) {

@ -1133,7 +1133,7 @@ Constant order means the number of operations is independent of the input data s
/* 常数阶 */
fun constant(n: Int): Int {
var count = 0
val size = 10_0000
val size = 100000
for (i in 0..<size)
count++
return count
@ -2056,7 +2056,7 @@ For instance, in bubble sort, the outer loop runs $n - 1$ times, and the inner l
```kotlin title="time_complexity.kt"
/* 平方阶(冒泡排序) */
fun bubbleSort(nums: IntArray): Int {
var count = 0
var count = 0 // 计数器
// 外循环:未排序区间为 [0, i]
for (i in nums.size - 1 downTo 1) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
@ -3119,7 +3119,7 @@ Linear-logarithmic order often appears in nested loops, with the complexities of
if (n <= 1)
return 1
var count = linearLogRecur(n / 2) + linearLogRecur(n / 2)
for (i in 0..<n.toInt()) {
for (i in 0..<n) {
count++
}
return count
@ -3747,10 +3747,9 @@ The "worst-case time complexity" corresponds to the asymptotic upper bound, deno
for (i in 0..<n) {
nums[i] = i + 1
}
// 随机打乱数组元素
val mutableList = nums.toMutableList()
// 随机打乱数组元素
mutableList.shuffle()
// Integer[] -> int[]
val res = arrayOfNulls<Int>(n)
for (i in 0..<n) {
res[i] = mutableList[i]

@ -143,7 +143,7 @@ Now we can answer the initial question: **The representation of `float` includes
**However, the trade-off for `float`'s expanded range is a sacrifice in precision**. The integer type `int` uses all 32 bits to represent the number, with values evenly distributed; but due to the exponent bit, the larger the value of a `float`, the greater the difference between adjacent numbers.
As shown in the Table 3-2 , exponent bits $E = 0$ and $E = 255$ have special meanings, **used to represent zero, infinity, $\mathrm{NaN}$, etc.**
As shown in the Table 3-2 , exponent bits $\mathrm{E} = 0$ and $\mathrm{E} = 255$ have special meanings, **used to represent zero, infinity, $\mathrm{NaN}$, etc.**
<p align="center"> Table 3-2 &nbsp; Meaning of exponent bits </p>

@ -2824,6 +2824,9 @@ The code below implements an open addressing (linear probing) hash table with la
free(pair);
}
}
free(hashMap->buckets);
free(hashMap->TOMBSTONE);
free(hashMap);
}
/* 哈希函数 */

@ -1797,8 +1797,8 @@ The implementation code is as follows:
if (fNext) {
fNext->prev = NULL;
deque->front->next = NULL;
delDoublyListNode(deque->front);
}
delDoublyListNode(deque->front);
deque->front = fNext; // 更新头节点
}
// 队尾出队操作
@ -1808,8 +1808,8 @@ The implementation code is as follows:
if (rPrev) {
rPrev->next = NULL;
deque->rear->prev = NULL;
delDoublyListNode(deque->rear);
}
delDoublyListNode(deque->rear);
deque->rear = rPrev; // 更新尾节点
}
deque->queSize--; // 更新队列长度

Loading…
Cancel
Save