This commit is contained in:
krahets 2023-09-03 19:14:37 +08:00
parent ca7b5c0ac2
commit f07e94ab0c
7 changed files with 95 additions and 8 deletions

View File

@ -315,9 +315,40 @@ status: new
=== "Swift"
```swift title="fractional_knapsack.swift"
[class]{Item}-[func]{}
/* 物品 */
class Item {
var w: Int // 物品重量
var v: Int // 物品价值
[class]{}-[func]{fractionalKnapsack}
init(w: Int, v: Int) {
self.w = w
self.v = v
}
}
/* 分数背包:贪心 */
func fractionalKnapsack(wgt: [Int], val: [Int], cap: Int) -> Double {
// 创建物品列表,包含两个属性:重量、价值
var items = zip(wgt, val).map { Item(w: $0, v: $1) }
// 按照单位价值 item.v / item.w 从高到低进行排序
items.sort(by: { -(Double($0.v) / Double($0.w)) < -(Double($1.v) / Double($1.w)) })
// 循环贪心选择
var res = 0.0
var cap = cap
for item in items {
if item.w <= cap {
// 若剩余容量充足,则将当前物品整个装进背包
res += Double(item.v)
cap -= item.w
} else {
// 若剩余容量不足,则将当前物品的一部分装进背包
res += Double(item.v) / Double(item.w) * Double(cap)
// 已无剩余容量,因此跳出循环
break
}
}
return res
}
```
=== "Zig"

View File

@ -196,7 +196,25 @@ status: new
=== "Swift"
```swift title="coin_change_greedy.swift"
[class]{}-[func]{coinChangeGreedy}
/* 零钱兑换:贪心 */
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
// 假设 coins 列表有序
var i = coins.count - 1
var count = 0
var amt = amt
// 循环进行贪心选择,直到无剩余金额
while amt > 0 {
// 找到小于且最接近剩余金额的硬币
while i > 0 && coins[i] > amt {
i -= 1
}
// 选择 coins[i]
amt -= coins[i]
count += 1
}
// 若未找到可行方案,则返回 -1
return amt == 0 ? count : -1
}
```
=== "Zig"

View File

@ -276,7 +276,26 @@ $$
=== "Swift"
```swift title="max_capacity.swift"
[class]{}-[func]{maxCapacity}
/* 最大容量:贪心 */
func maxCapacity(ht: [Int]) -> Int {
// 初始化 i, j 分列数组两端
var i = 0, j = ht.count - 1
// 初始最大容量为 0
var res = 0
// 循环贪心选择,直至两板相遇
while i < j {
// 更新最大容量
let cap = min(ht[i], ht[j]) * (j - i)
res = max(res, cap)
// 向内移动短板
if ht[i] < ht[j] {
i += 1
} else {
j -= 1
}
}
return res
}
```
=== "Zig"

View File

@ -253,7 +253,26 @@ $$
=== "Swift"
```swift title="max_product_cutting.swift"
[class]{}-[func]{maxProductCutting}
/* 最大切分乘积:贪心 */
func maxProductCutting(n: Int) -> Int {
// 当 n <= 3 时,必须切分出一个 1
if n <= 3 {
return 1 * (n - 1)
}
// 贪心地切分出 3 a 为 3 的个数b 为余数
let a = n / 3
let b = n % 3
if b == 1 {
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
return pow(3, a - 1) * 2 * 2
}
if b == 2 {
// 当余数为 2 时,不做处理
return pow(3, a) * 2
}
// 当余数为 0 时,不做处理
return pow(3, a)
}
```
=== "Zig"

View File

@ -86,7 +86,7 @@ comments: true
```python title="hash_map.py"
# 初始化哈希表
hmap: Dict = {}
hmap: dict = {}
# 添加操作
# 在哈希表中添加键值对 (key, value)

View File

@ -91,7 +91,7 @@ comments: true
```python title="deque.py"
# 初始化双向队列
deque: Deque[int] = collections.deque()
deque: deque[int] = collections.deque()
# 元素入队
deque.append(2) # 添加至队尾

View File

@ -88,7 +88,7 @@ comments: true
# 初始化队列
# 在 Python 中,我们一般将双向队列类 deque 看作队列使用
# 虽然 queue.Queue() 是纯正的队列类,但不太好用,因此不建议
que: Deque[int] = collections.deque()
que: deque[int] = collections.deque()
# 元素入队
que.append(1)