Format C, C++, C#, Go, Java, Python, Rust code.

This commit is contained in:
krahets
2023-09-02 23:54:38 +08:00
parent b6ac6aa7d7
commit dd72335235
53 changed files with 152 additions and 154 deletions

2
codes/c/.gitignore vendored
View File

@@ -6,4 +6,4 @@
!*/
*.dSYM/
build/
build/

View File

@@ -46,10 +46,10 @@ int comp(const void *a, const void *b) {
/* 求解子集和 II */
vector *subsetSumII(vector *nums, int target) {
vector *state = newVector(); // 状态(子集)
vector *state = newVector(); // 状态(子集)
qsort(nums->data, nums->size, sizeof(int *), comp); // 对 nums 进行排序
int start = 0; // 子集和
vector *res = newVector(); // 结果列表(子集列表)
int start = 0; // 子集和
vector *res = newVector(); // 结果列表(子集列表)
backtrack(state, target, nums, start, res);
return res;
}

View File

@@ -53,7 +53,7 @@ int bubbleSort(int *nums, int n) {
int count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for (int i = n - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]

View File

@@ -230,7 +230,7 @@ void removeVertex(graphAdjList *t, unsigned int index) {
Node *temp = vet->linked->head->next;
while (temp != 0) {
removeLink(temp->val->linked, vet); // 删除与该顶点有关的边
temp = temp->next;
temp = temp->next;
}
// 将顶点前移
@@ -241,7 +241,7 @@ void removeVertex(graphAdjList *t, unsigned int index) {
t->verticesList[t->size - 1] = 0; // 将被删除顶点的位置置 0
t->size--;
//释放被删除顶点的内存
// 释放内存
freeVertex(vet);
}
@@ -273,5 +273,5 @@ graphAdjList *newGraphAdjList(unsigned int verticesCapacity) {
newGraph->size = 0; // 初始化顶点数量
newGraph->capacity = verticesCapacity; // 初始化顶点容量
// 返回图指针
return newGraph;
return newGraph;
}

View File

@@ -49,8 +49,6 @@ void addVertex(graphAdjMat *t, int val) {
// 如果实际使用不大于预设空间,则直接初始化新空间
if (t->size < t->capacity) {
t->vertices[t->size] = val; // 初始化新顶点值
for (int i = 0; i < t->size; i++) {
t->adjMat[i][t->size] = 0; // 邻接矩新列阵置0
}
@@ -90,7 +88,7 @@ void addVertex(graphAdjMat *t, int val) {
free(t->adjMat);
// 扩容后,指向新地址
t->adjMat = tempMat; // 指向新的邻接矩阵地址
t->adjMat = tempMat; // 指向新的邻接矩阵地址
t->capacity = t->size * 2;
t->size++;
}
@@ -113,7 +111,7 @@ void removeVertex(graphAdjMat *t, unsigned int index) {
for (int j = index; j < t->size - 1; j++) {
t->adjMat[i][j] = t->adjMat[i][j + 1]; // 被删除列后的所有列前移
}
} else {
} else {
memcpy(t->adjMat[i], t->adjMat[i + 1], sizeof(unsigned int) * t->size); // 被删除行的下方所有行上移
for (int j = index; j < t->size; j++) {
t->adjMat[i][j] = t->adjMat[i][j + 1]; // 被删除列后的所有列前移
@@ -156,12 +154,12 @@ void printGraph(graphAdjMat *t) {
/* 构造函数 */
graphAdjMat *newGraphAjdMat(unsigned int numberVertices, int *vertices, unsigned int **adjMat) {
// 申请内存
graphAdjMat *newGraph = (graphAdjMat *)malloc(sizeof(graphAdjMat)); // 为图分配内存
newGraph->vertices = (int *)malloc(sizeof(int) * numberVertices * 2); // 为顶点列表分配内存
newGraph->adjMat = (unsigned int **)malloc(sizeof(unsigned int *) * numberVertices * 2); // 为邻接矩阵分配二维内存
graphAdjMat *newGraph = (graphAdjMat *)malloc(sizeof(graphAdjMat)); // 为图分配内存
newGraph->vertices = (int *)malloc(sizeof(int) * numberVertices * 2); // 为顶点列表分配内存
newGraph->adjMat = (unsigned int **)malloc(sizeof(unsigned int *) * numberVertices * 2); // 为邻接矩阵分配二维内存
unsigned int *temp = (unsigned int *)malloc(sizeof(unsigned int) * numberVertices * 2 * numberVertices * 2); // 为邻接矩阵分配一维内存
newGraph->size = numberVertices; // 初始化顶点数量
newGraph->capacity = numberVertices * 2; // 初始化图容量
newGraph->size = numberVertices; // 初始化顶点数量
newGraph->capacity = numberVertices * 2; // 初始化图容量
// 配置二维数组
for (int i = 0; i < numberVertices * 2; i++) {

View File

@@ -7,7 +7,7 @@
#include "../utils/common.h"
/* 哈希表默认数组大小 */
# define HASH_MAP_DEFAULT_SIZE 100
#define HASH_MAP_DEFAULT_SIZE 100
/* 键值对 int->string */
struct pair {
@@ -154,7 +154,7 @@ void print(ArrayHashMap *d) {
int i;
mapSet set;
pairSet(d, &set);
pair *entries = (pair*) set.set;
pair *entries = (pair *)set.set;
for (i = 0; i < set.len; i++) {
printf("%d -> %s\n", entries[i].key, entries[i].val);
}
@@ -164,7 +164,7 @@ void print(ArrayHashMap *d) {
/* Driver Code */
int main() {
/* 初始化哈希表 */
ArrayHashMap * map = newArrayHashMap();
ArrayHashMap *map = newArrayHashMap();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
@@ -178,7 +178,7 @@ int main() {
/* 查询操作 */
// 向哈希表输入键 key ,得到值 value
const char * name = get(map, 15937);
const char *name = get(map, 15937);
printf("\n输入学号 15937 ,查询到姓名 %s\n", name);
/* 删除操作 */
@@ -196,7 +196,7 @@ int main() {
mapSet set;
keySet(map, &set);
int *keys = (int*) set.set;
int *keys = (int *)set.set;
printf("\n单独遍历键 Key\n");
for (i = 0; i < set.len; i++) {
printf("%d\n", keys[i]);
@@ -204,12 +204,12 @@ int main() {
free(set.set);
valueSet(map, &set);
char **vals = (char**) set.set;
char **vals = (char **)set.set;
printf("\n单独遍历键 Value\n");
for (i = 0; i < set.len; i++) {
printf("%s\n", vals[i]);
}
free(set.set);
return 0;
}

View File

@@ -10,7 +10,7 @@
void bubbleSort(int nums[], int size) {
// 外循环:未排序区间为 [0, i]
for (int i = 0; i < size - 1; i++) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < size - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
@@ -26,7 +26,7 @@ void bubbleSortWithFlag(int nums[], int size) {
// 外循环:未排序区间为 [0, i]
for (int i = 0; i < size - 1; i++) {
bool flag = false;
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < size - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];

View File

@@ -14,7 +14,7 @@ void selectionSort(int nums[], int n) {
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // 记录最小元素的索引
k = j; // 记录最小元素的索引
}
// 将该最小元素与未排序区间的首个元素交换
int temp = nums[i];

View File

@@ -50,7 +50,7 @@ int bubbleSort(vector<int> &nums) {
int count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]

View File

@@ -31,7 +31,7 @@ void dfs(int i, vector<int> &src, vector<int> &buf, vector<int> &tar) {
}
/* 求解汉诺塔 */
void hanota(vector<int> &A, vector<int> &B, vector<int> &C) {
void solveHanota(vector<int> &A, vector<int> &B, vector<int> &C) {
int n = A.size();
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C);
@@ -52,7 +52,7 @@ int main() {
cout << "C =";
printVector(C);
hanota(A, B, C);
solveHanota(A, B, C);
cout << "圆盘移动完成后:\n";
cout << "A =";

View File

@@ -20,7 +20,7 @@ class HashMapChaining {
HashMapChaining() : size(0), capacity(4), loadThres(2.0 / 3), extendRatio(2) {
buckets.resize(capacity);
}
/* 析构方法 */
~HashMapChaining() {
for (auto &bucket : buckets) {

View File

@@ -31,7 +31,7 @@ int xorHash(string key) {
int hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
cout<<(int)c<<endl;
cout << (int)c << endl;
hash ^= (int)c;
}
return hash & MODULUS;

View File

@@ -10,7 +10,7 @@
void bubbleSort(vector<int> &nums) {
// 外循环:未排序区间为 [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
@@ -26,7 +26,7 @@ void bubbleSortWithFlag(vector<int> &nums) {
// 外循环:未排序区间为 [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
bool flag = false; // 初始化标志位
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
namespace hello_algo.chapter_backtracking;
public class subset_sum_i {
/* 回溯算法:子集和 I */

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
namespace hello_algo.chapter_backtracking;
public class subset_sum_i_naive {
/* 回溯算法:子集和 I */

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
namespace hello_algo.chapter_backtracking;
public class subset_sum_ii {
/* 回溯算法:子集和 II */

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_backtrack {
/* 回溯 */

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_dfs {
/* 搜索 */

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_dp {
/* 爬楼梯:动态规划 */

View File

@@ -4,13 +4,13 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
namespace hello_algo.chapter_dynamic_programming;
public class min_path_sum {
/* 最小路径和:暴力搜索 */
public int minPathSumDFS(int[][] grid, int i, int j) {
// 若为左上角单元格,则终止搜索
if (i == 0 && j == 0){
if (i == 0 && j == 0) {
return grid[0][0];
}
// 若行列索引越界,则返回 +∞ 代价

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_hashing;
namespace hello_algo.chapter_hashing;
public class built_in_hash {
[Test]

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_hashing;
namespace hello_algo.chapter_hashing;
public class simple_hash {
/* 加法哈希 */

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_heap;
namespace hello_algo.chapter_heap;
public class top_k {
/* 基于堆查找数组中最大的 k 个元素 */

View File

@@ -18,7 +18,7 @@ public class bucket_sort {
// 1. 将数组元素分配到各个桶中
foreach (float num in nums) {
// 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
int i = (int) (num * k);
int i = (int)(num * k);
// 将 num 添加进桶 i
buckets[i].Add(num);
}

View File

@@ -4,7 +4,7 @@
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_sorting;
namespace hello_algo.chapter_sorting;
public class heap_sort {
/* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */

View File

@@ -36,7 +36,7 @@ public class TreeNode {
/* 将列表反序列化为二叉树:递归 */
private static TreeNode? ListToTreeDFS(List<int?> arr, int i) {
if (i < 0|| i >= arr.Count || !arr[i].HasValue) {
if (i < 0 || i >= arr.Count || !arr[i].HasValue) {
return null;
}
TreeNode root = new TreeNode(arr[i].Value);

View File

@@ -28,7 +28,7 @@ void dfs(int i, List<int> src, List<int> buf, List<int> tar) {
}
/* 求解汉诺塔 */
void hanota(List<int> A, List<int> B, List<int> C) {
void solveHanota(List<int> A, List<int> B, List<int> C) {
int n = A.length;
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C);
@@ -45,7 +45,7 @@ void main() {
print("B = $B");
print("C = $C");
hanota(A, B, C);
solveHanota(A, B, C);
print("圆盘移动完成后:");
print("A = $A");

View File

@@ -64,4 +64,4 @@ func TestList(t *testing.T) {
/* 排序列表 */
sort.Ints(list) // 排序后,列表元素从小到大排列
fmt.Println("排序列表后 list =", list)
}
}

View File

@@ -43,4 +43,4 @@ func TestMyList(t *testing.T) {
list.add(i)
}
fmt.Printf("扩容后的列表 list = %v ,容量 = %v ,长度 = %v\n", list.toArray(), list.capacity(), list.size())
}
}

View File

@@ -6,8 +6,9 @@ package chapter_divide_and_conquer
import (
"fmt"
. "github.com/krahets/hello-algo/pkg"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestBuildTree(t *testing.T) {

View File

@@ -32,7 +32,7 @@ func dfsHanota(i int, src, buf, tar *list.List) {
}
/* 求解汉诺塔 */
func hanota(A, B, C *list.List) {
func solveHanota(A, B, C *list.List) {
n := A.Len()
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfsHanota(n, A, B, C)

View File

@@ -7,8 +7,9 @@ package chapter_divide_and_conquer
import (
"container/list"
"fmt"
. "github.com/krahets/hello-algo/pkg"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestHanota(t *testing.T) {
@@ -27,7 +28,7 @@ func TestHanota(t *testing.T) {
fmt.Print("C = ")
PrintList(C)
hanota(A, B, C)
solveHanota(A, B, C)
fmt.Println("圆盘移动完成后:")
fmt.Print("A = ")

View File

@@ -51,7 +51,7 @@ public class time_complexity {
int count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for (int i = nums.length - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]

View File

@@ -13,7 +13,7 @@ public class bubble_sort {
static void bubbleSort(int[] nums) {
// 外循环:未排序区间为 [0, i]
for (int i = nums.length - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
@@ -30,7 +30,7 @@ public class bubble_sort {
// 外循环:未排序区间为 [0, i]
for (int i = nums.length - 1; i > 0; i--) {
boolean flag = false; // 初始化标志位
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]

View File

@@ -28,7 +28,7 @@ function dfs(i, src, buf, tar) {
}
/* 求解汉诺塔 */
function hanota(A, B, C) {
function solveHanota(A, B, C) {
const n = A.length;
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C);
@@ -44,7 +44,7 @@ console.log(`A = ${JSON.stringify(A)}`);
console.log(`B = ${JSON.stringify(B)}`);
console.log(`C = ${JSON.stringify(C)}`);
hanota(A, B, C);
solveHanota(A, B, C);
console.log('圆盘移动完成后:');
console.log(`A = ${JSON.stringify(A)}`);

View File

@@ -46,7 +46,7 @@ def bubble_sort(nums: list[int]) -> int:
count = 0 # 计数器
# 外循环:未排序区间为 [0, i]
for i in range(len(nums) - 1, 0, -1):
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in range(i):
if nums[j] > nums[j + 1]:
# 交换 nums[j] 与 nums[j + 1]

View File

@@ -27,7 +27,7 @@ def dfs(i: int, src: list[int], buf: list[int], tar: list[int]):
dfs(i - 1, buf, src, tar)
def hanota(A: list[int], B: list[int], C: list[int]):
def solve_hanota(A: list[int], B: list[int], C: list[int]):
"""求解汉诺塔"""
n = len(A)
# 将 A 顶部 n 个圆盘借助 B 移到 C
@@ -45,7 +45,7 @@ if __name__ == "__main__":
print(f"B = {B}")
print(f"C = {C}")
hanota(A, B, C)
solve_hanota(A, B, C)
print("圆盘移动完成后:")
print(f"A = {A}")

View File

@@ -20,7 +20,7 @@ if __name__ == "__main__":
print(f"布尔量 {bol} 的哈希值为 {hash_bol}")
dec = 3.14159
hash_dec = hash(dec)
hash_dec = hash(dec)
print(f"小数 {dec} 的哈希值为 {hash_dec}")
str = "Hello 算法"

View File

@@ -33,5 +33,5 @@ if __name__ == "__main__":
k = 3
res = top_k_heap(nums, k)
print(f"最大的 {k} 个元素为")
print(f"最大的 {k} 个元素为")
print_heap(res)

View File

@@ -10,7 +10,7 @@ def bubble_sort(nums: list[int]):
n = len(nums)
# 外循环:未排序区间为 [0, i]
for i in range(n - 1, 0, -1):
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in range(i):
if nums[j] > nums[j + 1]:
# 交换 nums[j] 与 nums[j + 1]
@@ -23,7 +23,7 @@ def bubble_sort_with_flag(nums: list[int]):
# 外循环:未排序区间为 [0, i]
for i in range(n - 1, 0, -1):
flag = False # 初始化标志位
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
# 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in range(i):
if nums[j] > nums[j + 1]:
# 交换 nums[j] 与 nums[j + 1]

View File

@@ -36,7 +36,7 @@ def heap_sort(nums: list[int]):
nums[0], nums[i] = nums[i], nums[0]
# 以根节点为起点,从顶至底进行堆化
sift_down(nums, i, 0)
"""Driver Code"""
if __name__ == "__main__":

View File

@@ -35,9 +35,7 @@ def show_trunks(p: Trunk | None):
print(p.str, end="")
def print_tree(
root: TreeNode | None, prev: Trunk | None = None, is_left: bool = False
):
def print_tree(root: TreeNode | None, prev: Trunk | None = None, is_left: bool = False):
"""
Print a binary tree
This tree printer is borrowed from TECHIE DELIGHT

View File

@@ -8,68 +8,68 @@ include!("../include/include.rs");
/* Driver Code */
fn main() {
// 初始化列表
let mut list: Vec<i32> = vec![ 1, 3, 2, 5, 4 ];
print!("列表 list = ");
print_util::print_array(&list);
// 初始化列表
let mut list: Vec<i32> = vec![ 1, 3, 2, 5, 4 ];
print!("列表 list = ");
print_util::print_array(&list);
// 访问元素
let num = list[1];
println!("\n访问索引 1 处的元素,得到 num = {num}");
// 访问元素
let num = list[1];
println!("\n访问索引 1 处的元素,得到 num = {num}");
// 更新元素
list[1] = 0;
print!("将索引 1 处的元素更新为 0 ,得到 list = ");
print_util::print_array(&list);
// 更新元素
list[1] = 0;
print!("将索引 1 处的元素更新为 0 ,得到 list = ");
print_util::print_array(&list);
// 清空列表
list.clear();
print!("\n清空列表后 list = ");
print_util::print_array(&list);
// 清空列表
list.clear();
print!("\n清空列表后 list = ");
print_util::print_array(&list);
// 尾部添加元素
list.push(1);
list.push(3);
list.push(2);
list.push(5);
list.push(4);
print!("\n添加元素后 list = ");
print_util::print_array(&list);
// 尾部添加元素
list.push(1);
list.push(3);
list.push(2);
list.push(5);
list.push(4);
print!("\n添加元素后 list = ");
print_util::print_array(&list);
// 中间插入元素
list.insert(3, 6);
print!("\n在索引 3 处插入数字 6 ,得到 list = ");
print_util::print_array(&list);
// 中间插入元素
list.insert(3, 6);
print!("\n在索引 3 处插入数字 6 ,得到 list = ");
print_util::print_array(&list);
// 删除元素
list.remove(3);
print!("\n删除索引 3 处的元素,得到 list = ");
print_util::print_array(&list);
// 删除元素
list.remove(3);
print!("\n删除索引 3 处的元素,得到 list = ");
print_util::print_array(&list);
// 通过索引遍历列表
let mut _count = 0;
for _ in 0..list.len() {
_count += 1;
}
// 通过索引遍历列表
let mut _count = 0;
for _ in 0..list.len() {
_count += 1;
}
// 直接遍历列表元素
_count = 0;
for _n in &list {
_count += 1;
}
// 或者
// list.iter().for_each(|_| _count += 1);
// let _count = list.iter().fold(0, |_count, _| _count + 1);
// 直接遍历列表元素
_count = 0;
for _n in &list {
_count += 1;
}
// 或者
// list.iter().for_each(|_| _count += 1);
// let _count = list.iter().fold(0, |_count, _| _count + 1);
// 拼接两个列表
let mut list1 = vec![ 6, 8, 7, 10, 9 ];
list.append(&mut list1); // append移动 之后 list1 为空!
// list.extend(&list1); // extend借用 list1 能继续使用
print!("\n将列表 list1 拼接到 list 之后,得到 list = ");
print_util::print_array(&list);
// 拼接两个列表
let mut list1 = vec![ 6, 8, 7, 10, 9 ];
list.append(&mut list1); // append移动 之后 list1 为空!
// list.extend(&list1); // extend借用 list1 能继续使用
print!("\n将列表 list1 拼接到 list 之后,得到 list = ");
print_util::print_array(&list);
// 排序列表
list.sort();
print!("\n排序列表后 list = ");
print_util::print_array(&list);
// 排序列表
list.sort();
print!("\n排序列表后 list = ");
print_util::print_array(&list);
}

View File

@@ -4,7 +4,7 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
include!("../include/include.rs");
include!("../include/include.rs");
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};

View File

@@ -4,7 +4,7 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
include!("../include/include.rs");
include!("../include/include.rs");
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};

View File

@@ -4,7 +4,7 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
include!("../include/include.rs");
include!("../include/include.rs");
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};

View File

@@ -4,7 +4,7 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
include!("../include/include.rs");
include!("../include/include.rs");
use std::{cell::RefCell, rc::Rc};
use tree_node::{vec_to_tree, TreeNode};

View File

@@ -30,7 +30,7 @@ fn dfs(i: i32, src: &mut Vec<i32>, buf: &mut Vec<i32>, tar: &mut Vec<i32>) {
}
/* 求解汉诺塔 */
fn hanota(A: &mut Vec<i32>, B: &mut Vec<i32>, C: &mut Vec<i32>) {
fn solve_hanota(A: &mut Vec<i32>, B: &mut Vec<i32>, C: &mut Vec<i32>) {
let n = A.len() as i32;
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C);
@@ -46,7 +46,7 @@ pub fn main() {
println!("B = {:?}", B);
println!("C = {:?}", C);
hanota(&mut A, &mut B, &mut C);
solve_hanota(&mut A, &mut B, &mut C);
println!("圆盘移动完成后:");
println!("A = {:?}", A);

View File

@@ -4,7 +4,7 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
use std::cmp;
use std::cmp;
/* 爬楼梯最小代价:动态规划 */
fn min_cost_climbing_stairs_dp(cost: &[i32]) -> i32 {

View File

@@ -4,12 +4,12 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
include!("../include/include.rs");
include!("../include/include.rs");
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
/* 哈希查找(数组) */
fn hashing_search_array<'a>(map: &'a HashMap<i32, usize>, target: i32) -> Option<&'a usize> {

View File

@@ -4,11 +4,11 @@
* Author: sjinzh (sjinzh@gmail.com)
*/
include!("../include/include.rs");
include!("../include/include.rs");
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
use std::rc::Rc;
use std::cell::RefCell;
use list_node::ListNode;
/* 线性查找(数组) */
fn linear_search_array(nums: &[i32], target: i32) -> i32 {

View File

@@ -28,7 +28,7 @@ function dfs(i: number, src: number[], buf: number[], tar: number[]): void {
}
/* 求解汉诺塔 */
function hanota(A: number[], B: number[], C: number[]): void {
function solveHanota(A: number[], B: number[], C: number[]): void {
const n = A.length;
// 将 A 顶部 n 个圆盘借助 B 移到 C
dfs(n, A, B, C);
@@ -44,7 +44,7 @@ console.log(`A = ${JSON.stringify(A)}`);
console.log(`B = ${JSON.stringify(B)}`);
console.log(`C = ${JSON.stringify(C)}`);
hanota(A, B, C);
solveHanota(A, B, C);
console.log('圆盘移动完成后:');
console.log(`A = ${JSON.stringify(A)}`);

View File

@@ -99,7 +99,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "Python"
@@ -109,7 +109,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solve_hanota}
```
=== "Go"
@@ -119,7 +119,7 @@
[class]{}-[func]{dfsHanota}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "JS"
@@ -129,7 +129,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "TS"
@@ -139,7 +139,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "C"
@@ -149,7 +149,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "C#"
@@ -169,7 +169,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "Zig"
@@ -179,7 +179,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "Dart"
@@ -189,7 +189,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solveHanota}
```
=== "Rust"
@@ -199,7 +199,7 @@
[class]{}-[func]{dfs}
[class]{}-[func]{hanota}
[class]{}-[func]{solve_hanota}
```
如下图所示,汉诺塔问题形成一个高度为 $n$ 的递归树,每个节点代表一个子问题、对应一个开启的 `dfs()` 函数,**因此时间复杂度为 $O(2^n)$ ,空间复杂度为 $O(n)$** 。