mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-12 23:36:06 +00:00
build
This commit is contained in:
@@ -99,7 +99,12 @@ comments: true
|
||||
|
||||
```rust title="array.rs"
|
||||
/* 初始化数组 */
|
||||
let arr: Vec<i32> = vec![0; 5]; // [0, 0, 0, 0, 0]
|
||||
let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0]
|
||||
let slice: &[i32] = &[0; 5];
|
||||
// 在 Rust 中,指定长度时([i32; 5])为数组,不指定长度时(&[i32])为切片
|
||||
// 由于 Rust 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度
|
||||
// Vector 是 Rust 一般情况下用作动态数组的类型
|
||||
// 为了方便实现扩容 extend() 方法,以下将 vector 看作数组(array)
|
||||
let nums: Vec<i32> = vec![1, 3, 2, 5, 4];
|
||||
```
|
||||
|
||||
@@ -477,7 +482,7 @@ comments: true
|
||||
|
||||
```rust title="array.rs"
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
fn insert(nums: &mut Vec<i32>, num: i32, index: usize) {
|
||||
fn insert(nums: &mut [i32], num: i32, index: usize) {
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for i in (index + 1..nums.len()).rev() {
|
||||
nums[i] = nums[i - 1];
|
||||
@@ -670,7 +675,7 @@ comments: true
|
||||
|
||||
```rust title="array.rs"
|
||||
/* 删除索引 index 处的元素 */
|
||||
fn remove(nums: &mut Vec<i32>, index: usize) {
|
||||
fn remove(nums: &mut [i32], index: usize) {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for i in index..nums.len() - 1 {
|
||||
nums[i] = nums[i + 1];
|
||||
@@ -1350,7 +1355,7 @@ comments: true
|
||||
|
||||
```rust title="array.rs"
|
||||
/* 扩展数组长度 */
|
||||
fn extend(nums: Vec<i32>, enlarge: usize) -> Vec<i32> {
|
||||
fn extend(nums: &[i32], enlarge: usize) -> Vec<i32> {
|
||||
// 初始化一个扩展长度后的数组
|
||||
let mut res: Vec<i32> = vec![0; nums.len() + enlarge];
|
||||
// 将原数组中的所有元素复制到新
|
||||
|
||||
@@ -77,4 +77,4 @@ comments: true
|
||||
|
||||
**Q**:初始化列表 `res = [0] * self.size()` 操作,会导致 `res` 的每个元素引用相同的地址吗?
|
||||
|
||||
不会。但二维数组会有这个问题,例如初始化二维列表 `res = [[0] * self.size()]` ,则多次引用了同一个列表 `[0]` 。
|
||||
不会。但二维数组会有这个问题,例如初始化二维列表 `res = [[0]] * self.size()` ,则多次引用了同一个列表 `[0]` 。
|
||||
|
||||
@@ -422,9 +422,32 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search_recur.rb"
|
||||
[class]{}-[func]{dfs}
|
||||
### 二分查找:问题 f(i, j) ###
|
||||
def dfs(nums, target, i, j)
|
||||
# 若区间为空,代表无目标元素,则返回 -1
|
||||
return -1 if i > j
|
||||
|
||||
# 计算中点索引 m
|
||||
m = (i + j) / 2
|
||||
|
||||
[class]{}-[func]{binary_search}
|
||||
if nums[m] < target
|
||||
# 递归子问题 f(m+1, j)
|
||||
return dfs(nums, target, m + 1, j)
|
||||
elsif nums[m] > target
|
||||
# 递归子问题 f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1)
|
||||
else
|
||||
# 找到目标元素,返回其索引
|
||||
return m
|
||||
end
|
||||
end
|
||||
|
||||
### 二分查找 ###
|
||||
def binary_search(nums, target)
|
||||
n = nums.length
|
||||
# 求解问题 f(0, n-1)
|
||||
dfs(nums, target, 0, n - 1)
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -485,9 +485,31 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="build_tree.rb"
|
||||
[class]{}-[func]{dfs}
|
||||
### 构建二叉树:分治 ###
|
||||
def dfs(preorder, inorder_map, i, l, r)
|
||||
# 子树区间为空时终止
|
||||
return if r - l < 0
|
||||
|
||||
[class]{}-[func]{build_tree}
|
||||
# 初始化根节点
|
||||
root = TreeNode.new(preorder[i])
|
||||
# 查询 m ,从而划分左右子树
|
||||
m = inorder_map[preorder[i]]
|
||||
# 子问题:构建左子树
|
||||
root.left = dfs(preorder, inorder_map, i + 1, l, m - 1)
|
||||
# 子问题:构建右子树
|
||||
root.right = dfs(preorder, inorder_map, i + 1 + m - l, m + 1, r)
|
||||
|
||||
# 返回根节点
|
||||
root
|
||||
end
|
||||
|
||||
### 构建二叉树 ###
|
||||
def build_tree(preorder, inorder)
|
||||
# 初始化哈希表,存储 inorder 元素到索引的映射
|
||||
inorder_map = {}
|
||||
inorder.each_with_index { |val, i| inorder_map[val] = i }
|
||||
dfs(preorder, inorder_map, 0, 0, inorder.length - 1)
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -409,7 +409,7 @@ comments: true
|
||||
/* 移动一个圆盘 */
|
||||
fn move_pan(src: &mut Vec<i32>, tar: &mut Vec<i32>) {
|
||||
// 从 src 顶部拿出一个圆盘
|
||||
let pan = src.remove(src.len() - 1);
|
||||
let pan = src.pop().unwrap();
|
||||
// 将圆盘放入 tar 顶部
|
||||
tar.push(pan);
|
||||
}
|
||||
@@ -510,11 +510,36 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="hanota.rb"
|
||||
[class]{}-[func]{move}
|
||||
### 移动一个圆盘 ###
|
||||
def move(src, tar)
|
||||
# 从 src 顶部拿出一个圆盘
|
||||
pan = src.pop
|
||||
# 将圆盘放入 tar 顶部
|
||||
tar << pan
|
||||
end
|
||||
|
||||
[class]{}-[func]{dfs}
|
||||
### 求解汉诺塔问题 f(i) ###
|
||||
def dfs(i, src, buf, tar)
|
||||
# 若 src 只剩下一个圆盘,则直接将其移到 tar
|
||||
if i == 1
|
||||
move(src, tar)
|
||||
return
|
||||
end
|
||||
|
||||
[class]{}-[func]{solve_hanota}
|
||||
# 子问题 f(i-1) :将 src 顶部 i-1 个圆盘借助 tar 移到 buf
|
||||
dfs(i - 1, src, tar, buf)
|
||||
# 子问题 f(1) :将 src 剩余一个圆盘移到 tar
|
||||
move(src, tar)
|
||||
# 子问题 f(i-1) :将 buf 顶部 i-1 个圆盘借助 src 移到 tar
|
||||
dfs(i - 1, buf, src, tar)
|
||||
end
|
||||
|
||||
### 求解汉诺塔问题 ###
|
||||
def solve_hanota(_A, _B, _C)
|
||||
n = _A.length
|
||||
# 将 A 顶部 n 个圆盘借助 B 移到 C
|
||||
dfs(n, _A, _B, _C)
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -496,9 +496,39 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="fractional_knapsack.rb"
|
||||
[class]{Item}-[func]{}
|
||||
### 物品 ###
|
||||
class Item
|
||||
attr_accessor :w # 物品重量
|
||||
attr_accessor :v # 物品价值
|
||||
|
||||
[class]{}-[func]{fractional_knapsack}
|
||||
def initialize(w, v)
|
||||
@w = w
|
||||
@v = v
|
||||
end
|
||||
end
|
||||
|
||||
### 分数背包:贪心 ###
|
||||
def fractional_knapsack(wgt, val, cap)
|
||||
# 创建物品列表,包含两个属性:重量,价值
|
||||
items = wgt.each_with_index.map { |w, i| Item.new(w, val[i]) }
|
||||
# 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
items.sort! { |a, b| (b.v.to_f / b.w) <=> (a.v.to_f / a.w) }
|
||||
# 循环贪心选择
|
||||
res = 0
|
||||
for item in items
|
||||
if item.w <= cap
|
||||
# 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v
|
||||
cap -= item.w
|
||||
else
|
||||
# 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (item.v.to_f / item.w) * cap
|
||||
# 已无剩余容量,因此跳出循环
|
||||
break
|
||||
end
|
||||
end
|
||||
res
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -310,7 +310,24 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="coin_change_greedy.rb"
|
||||
[class]{}-[func]{coin_change_greedy}
|
||||
### 零钱兑换:贪心 ###
|
||||
def coin_change_greedy(coins, amt)
|
||||
# 假设 coins 列表有序
|
||||
i = coins.length - 1
|
||||
count = 0
|
||||
# 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0
|
||||
# 找到小于且最接近剩余金额的硬币
|
||||
while i > 0 && coins[i] > amt
|
||||
i -= 1
|
||||
end
|
||||
# 选择 coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
end
|
||||
# 若未找到可行方案, 则返回 -1
|
||||
amt == 0 ? count : -1
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -397,7 +397,28 @@ $$
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="max_capacity.rb"
|
||||
[class]{}-[func]{max_capacity}
|
||||
### 最大容量:贪心 ###
|
||||
def max_capacity(ht)
|
||||
# 初始化 i, j,使其分列数组两端
|
||||
i, j = 0, ht.length - 1
|
||||
# 初始最大容量为 0
|
||||
res = 0
|
||||
|
||||
# 循环贪心选择,直至两板相遇
|
||||
while i < j
|
||||
# 更新最大容量
|
||||
cap = [ht[i], ht[j]].min * (j - i)
|
||||
res = [res, cap].max
|
||||
# 向内移动短板
|
||||
if ht[i] < ht[j]
|
||||
i += 1
|
||||
else
|
||||
j -= 1
|
||||
end
|
||||
end
|
||||
|
||||
res
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -371,7 +371,19 @@ $$
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="max_product_cutting.rb"
|
||||
[class]{}-[func]{max_product_cutting}
|
||||
### 最大切分乘积:贪心 ###
|
||||
def max_product_cutting(n)
|
||||
# 当 n <= 3 时,必须切分出一个 1
|
||||
return 1 * (n - 1) if n <= 3
|
||||
# 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
a, b = n / 3, n % 3
|
||||
# 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return (3.pow(a - 1) * 2 * 2).to_i if b == 1
|
||||
# 当余数为 2 时,不做处理
|
||||
return (3.pow(a) * 2).to_i if b == 2
|
||||
# 当余数为 0 时,不做处理
|
||||
3.pow(a).to_i
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
@@ -14,7 +14,7 @@ comments: true
|
||||
|
||||
## 1.2.2 数据结构定义
|
||||
|
||||
<u>数据结构(data structure)</u>是计算机中组织和存储数据的方式,具有以下设计目标。
|
||||
<u>数据结构(data structure)</u>是组织和存储数据的方式,涵盖数据内容、数据之间关系和数据操作方法,它具有以下设计目标。
|
||||
|
||||
- 空间占用尽量少,以节省计算机内存。
|
||||
- 数据操作尽可能快速,涵盖数据访问、添加、删除、更新等。
|
||||
|
||||
@@ -225,9 +225,7 @@ comments: true
|
||||
for j in 0..i {
|
||||
if nums[j] > nums[j + 1] {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
nums.swap(j, j + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -538,9 +536,7 @@ comments: true
|
||||
for j in 0..i {
|
||||
if nums[j] > nums[j + 1] {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
nums.swap(j, j + 1);
|
||||
flag = true; // 记录交换元素
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ comments: true
|
||||
let k = nums.len() / 2;
|
||||
let mut buckets = vec![vec![]; k];
|
||||
// 1. 将数组元素分配到各个桶中
|
||||
for &mut num in &mut *nums {
|
||||
for &num in nums.iter() {
|
||||
// 输入数据范围为 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
|
||||
let i = (num * k as f64) as usize;
|
||||
// 将 num 添加进桶 i
|
||||
@@ -327,8 +327,8 @@ comments: true
|
||||
}
|
||||
// 3. 遍历桶合并结果
|
||||
let mut i = 0;
|
||||
for bucket in &mut buckets {
|
||||
for &mut num in bucket {
|
||||
for bucket in buckets.iter() {
|
||||
for &num in bucket.iter() {
|
||||
nums[i] = num;
|
||||
i += 1;
|
||||
}
|
||||
|
||||
@@ -266,11 +266,11 @@ comments: true
|
||||
// 简单实现,无法用于排序对象
|
||||
fn counting_sort_naive(nums: &mut [i32]) {
|
||||
// 1. 统计数组最大元素 m
|
||||
let m = *nums.into_iter().max().unwrap();
|
||||
let m = *nums.iter().max().unwrap();
|
||||
// 2. 统计各数字的出现次数
|
||||
// counter[num] 代表 num 的出现次数
|
||||
let mut counter = vec![0; m as usize + 1];
|
||||
for &num in &*nums {
|
||||
for &num in nums.iter() {
|
||||
counter[num as usize] += 1;
|
||||
}
|
||||
// 3. 遍历 counter ,将各元素填入原数组 nums
|
||||
@@ -764,16 +764,16 @@ $$
|
||||
// 完整实现,可排序对象,并且是稳定排序
|
||||
fn counting_sort(nums: &mut [i32]) {
|
||||
// 1. 统计数组最大元素 m
|
||||
let m = *nums.into_iter().max().unwrap();
|
||||
let m = *nums.iter().max().unwrap() as usize;
|
||||
// 2. 统计各数字的出现次数
|
||||
// counter[num] 代表 num 的出现次数
|
||||
let mut counter = vec![0; m as usize + 1];
|
||||
for &num in &*nums {
|
||||
let mut counter = vec![0; m + 1];
|
||||
for &num in nums.iter() {
|
||||
counter[num as usize] += 1;
|
||||
}
|
||||
// 3. 求 counter 的前缀和,将“出现次数”转换为“尾索引”
|
||||
// 即 counter[num]-1 是 num 在 res 中最后一次出现的索引
|
||||
for i in 0..m as usize {
|
||||
for i in 0..m {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. 倒序遍历 nums ,将各元素填入结果数组 res
|
||||
@@ -786,9 +786,7 @@ $$
|
||||
counter[num as usize] -= 1; // 令前缀和自减 1 ,得到下次放置 num 的索引
|
||||
}
|
||||
// 使用结果数组 res 覆盖原数组 nums
|
||||
for i in 0..n {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
nums.copy_from_slice(&res)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -463,9 +463,7 @@ comments: true
|
||||
break;
|
||||
}
|
||||
// 交换两节点
|
||||
let temp = nums[i];
|
||||
nums[i] = nums[ma];
|
||||
nums[ma] = temp;
|
||||
nums.swap(i, ma);
|
||||
// 循环向下堆化
|
||||
i = ma;
|
||||
}
|
||||
@@ -474,15 +472,13 @@ comments: true
|
||||
/* 堆排序 */
|
||||
fn heap_sort(nums: &mut [i32]) {
|
||||
// 建堆操作:堆化除叶节点以外的其他所有节点
|
||||
for i in (0..=nums.len() / 2 - 1).rev() {
|
||||
for i in (0..nums.len() / 2).rev() {
|
||||
sift_down(nums, nums.len(), i);
|
||||
}
|
||||
// 从堆中提取最大元素,循环 n-1 轮
|
||||
for i in (1..=nums.len() - 1).rev() {
|
||||
for i in (1..nums.len()).rev() {
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
let tmp = nums[0];
|
||||
nums[0] = nums[i];
|
||||
nums[i] = tmp;
|
||||
nums.swap(0, i);
|
||||
// 以根节点为起点,从顶至底进行堆化
|
||||
sift_down(nums, i, 0);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user