mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-28 07:21:55 +08:00
Update the five translated editions of Hello Algo (#2052)
* Preserve the published Taiwan figure descriptions and homepage as editable sources * Update the five translated editions of Hello Algo * Fix reviewed translation, diagram, and example errors across the book * Correct Korean reader grammar, native diagnostics and example output
This commit is contained in:
@@ -13,7 +13,7 @@ int coinChangeGreedy(int *coins, int size, int amt) {
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
typedef struct {
|
||||
int *nums; // 用于存储队列元素的数组
|
||||
int front; // 队首指针,指向队首元素
|
||||
int queSize; // 尾指针,指向队尾 + 1
|
||||
int queSize; // 双端队列中的元素个数
|
||||
int queCapacity; // 队列容量
|
||||
} ArrayDeque;
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ int coinChangeGreedy(vector<int> &coins, int amt) {
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ public class coin_change_greedy {
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,6 @@ void main() {
|
||||
final nums = randomNumbers(n);
|
||||
int index = findOne(nums);
|
||||
print('\n数组 [ 1, 2, ..., n ] 被打乱后 = $nums');
|
||||
print('数字 1 的索引为 + $index');
|
||||
print('数字 1 的索引为 $index');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ int coinChangeGreedy(List<int> coins, int amt) {
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ class MinHeap {
|
||||
int mi = i;
|
||||
if (l < size() && _minHeap[l] < _minHeap[mi]) mi = l;
|
||||
if (r < size() && _minHeap[r] < _minHeap[mi]) mi = r;
|
||||
// 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
|
||||
// 若没有子节点的值小于父节点的值,则停止下沉
|
||||
if (mi == i) break;
|
||||
// 交换两节点
|
||||
_swap(i, mi);
|
||||
|
||||
@@ -13,8 +13,8 @@ func TestNQueens(t *testing.T) {
|
||||
n := 4
|
||||
res := nQueens(n)
|
||||
|
||||
fmt.Println("输入棋盘长宽为 ", n)
|
||||
fmt.Println("皇后放置方案共有 ", len(res), " 种")
|
||||
fmt.Println("输入棋盘长宽为", n)
|
||||
fmt.Println("皇后放置方案共有", len(res), "种")
|
||||
for _, state := range res {
|
||||
fmt.Println("--------------------")
|
||||
for _, row := range state {
|
||||
|
||||
@@ -11,7 +11,7 @@ func coinChangeGreedy(coins []int, amt int) int {
|
||||
count := 0
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
for amt > 0 {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
for i > 0 && coins[i] > amt {
|
||||
i--
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func (q *arrayQueue) isEmpty() bool {
|
||||
|
||||
/* 入队 */
|
||||
func (q *arrayQueue) push(num int) {
|
||||
// 当 rear == queCapacity 表示队列已满
|
||||
// 当 queSize == queCapacity 表示队列已满
|
||||
if q.queSize == q.queCapacity {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ public class coin_change_greedy {
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ function coinChangeGreedy(coins, amt) {
|
||||
let count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ fun coinChangeGreedy(coins: IntArray, amt: Int): Int {
|
||||
var count = 0
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (am > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > am) {
|
||||
i--
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ package chapter_greedy
|
||||
|
||||
/* 物品 */
|
||||
class Item(
|
||||
val w: Int, // 物品
|
||||
val w: Int, // 物品重量
|
||||
val v: Int // 物品价值
|
||||
)
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ fun maxProductCutting(n: Int): Int {
|
||||
}
|
||||
if (b == 2) {
|
||||
// 当余数为 2 时,不做处理
|
||||
return 3.0.pow(a).toInt() * 2 * 2
|
||||
return 3.0.pow(a).toInt() * 2
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return 3.0.pow(a).toInt()
|
||||
|
||||
@@ -12,7 +12,7 @@ def coin_change_greedy(coins: list[int], amt: int) -> int:
|
||||
count = 0
|
||||
# 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0:
|
||||
# 找到小于且最接近剩余金额的硬币
|
||||
# 找到不超过剩余金额的最大面额
|
||||
while i > 0 and coins[i] > amt:
|
||||
i -= 1
|
||||
# 选择 coins[i]
|
||||
|
||||
@@ -5,4 +5,4 @@
|
||||
--->
|
||||
|
||||
<!-- [file]{coin_change_greedy}-[class]{}-[func]{coin_change_greedy} -->
|
||||
https://pythontutor.com/render.html#code=def%20coin_change_greedy%28coins%3A%20list%5Bint%5D,%20amt%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2%EF%BC%9A%E8%B4%AA%E5%BF%83%22%22%22%0A%20%20%20%20%23%20%E5%81%87%E8%AE%BE%20coins%20%E5%88%97%E8%A1%A8%E6%9C%89%E5%BA%8F%0A%20%20%20%20i%20%3D%20len%28coins%29%20-%201%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20%23%20%E5%BE%AA%E7%8E%AF%E8%BF%9B%E8%A1%8C%E8%B4%AA%E5%BF%83%E9%80%89%E6%8B%A9%EF%BC%8C%E7%9B%B4%E5%88%B0%E6%97%A0%E5%89%A9%E4%BD%99%E9%87%91%E9%A2%9D%0A%20%20%20%20while%20amt%20%3E%200%3A%0A%20%20%20%20%20%20%20%20%23%20%E6%89%BE%E5%88%B0%E5%B0%8F%E4%BA%8E%E4%B8%94%E6%9C%80%E6%8E%A5%E8%BF%91%E5%89%A9%E4%BD%99%E9%87%91%E9%A2%9D%E7%9A%84%E7%A1%AC%E5%B8%81%0A%20%20%20%20%20%20%20%20while%20i%20%3E%200%20and%20coins%5Bi%5D%20%3E%20amt%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20-%3D%201%0A%20%20%20%20%20%20%20%20%23%20%E9%80%89%E6%8B%A9%20coins%5Bi%5D%0A%20%20%20%20%20%20%20%20amt%20-%3D%20coins%5Bi%5D%0A%20%20%20%20%20%20%20%20count%20%2B%3D%201%0A%20%20%20%20%23%20%E8%8B%A5%E6%9C%AA%E6%89%BE%E5%88%B0%E5%8F%AF%E8%A1%8C%E6%96%B9%E6%A1%88%EF%BC%8C%E5%88%99%E8%BF%94%E5%9B%9E%20-1%0A%20%20%20%20return%20count%20if%20amt%20%3D%3D%200%20else%20-1%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E8%B4%AA%E5%BF%83%EF%BC%9A%E8%83%BD%E5%A4%9F%E4%BF%9D%E8%AF%81%E6%89%BE%E5%88%B0%E5%85%A8%E5%B1%80%E6%9C%80%E4%BC%98%E8%A7%A3%0A%20%20%20%20coins%20%3D%20%5B1,%205,%2010,%2020,%2050,%20100%5D%0A%20%20%20%20amt%20%3D%20186%0A%20%20%20%20res%20%3D%20coin_change_greedy%28coins,%20amt%29%0A%20%20%20%20print%28f%22%5Cncoins%20%3D%20%7Bcoins%7D,%20amt%20%3D%20%7Bamt%7D%22%29%0A%20%20%20%20print%28f%22%E5%87%91%E5%88%B0%20%7Bamt%7D%20%E6%89%80%E9%9C%80%E7%9A%84%E6%9C%80%E5%B0%91%E7%A1%AC%E5%B8%81%E6%95%B0%E9%87%8F%E4%B8%BA%20%7Bres%7D%22%29%0A%0A%20%20%20%20%23%20%E8%B4%AA%E5%BF%83%EF%BC%9A%E6%97%A0%E6%B3%95%E4%BF%9D%E8%AF%81%E6%89%BE%E5%88%B0%E5%85%A8%E5%B1%80%E6%9C%80%E4%BC%98%E8%A7%A3%0A%20%20%20%20coins%20%3D%20%5B1,%2020,%2050%5D%0A%20%20%20%20amt%20%3D%2060%0A%20%20%20%20res%20%3D%20coin_change_greedy%28coins,%20amt%29%0A%20%20%20%20print%28f%22%5Cncoins%20%3D%20%7Bcoins%7D,%20amt%20%3D%20%7Bamt%7D%22%29%0A%20%20%20%20print%28f%22%E5%87%91%E5%88%B0%20%7Bamt%7D%20%E6%89%80%E9%9C%80%E7%9A%84%E6%9C%80%E5%B0%91%E7%A1%AC%E5%B8%81%E6%95%B0%E9%87%8F%E4%B8%BA%20%7Bres%7D%22%29%0A%20%20%20%20print%28f%22%E5%AE%9E%E9%99%85%E4%B8%8A%E9%9C%80%E8%A6%81%E7%9A%84%E6%9C%80%E5%B0%91%E6%95%B0%E9%87%8F%E4%B8%BA%203%20%EF%BC%8C%E5%8D%B3%2020%20%2B%2020%20%2B%2020%22%29&cumulative=false&curInstr=5&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
|
||||
https://pythontutor.com/render.html#code=def%20coin_change_greedy%28coins%3A%20list%5Bint%5D,%20amt%3A%20int%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2%EF%BC%9A%E8%B4%AA%E5%BF%83%22%22%22%0A%20%20%20%20%23%20%E5%81%87%E8%AE%BE%20coins%20%E5%88%97%E8%A1%A8%E6%9C%89%E5%BA%8F%0A%20%20%20%20i%20%3D%20len%28coins%29%20-%201%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20%23%20%E5%BE%AA%E7%8E%AF%E8%BF%9B%E8%A1%8C%E8%B4%AA%E5%BF%83%E9%80%89%E6%8B%A9%EF%BC%8C%E7%9B%B4%E5%88%B0%E6%97%A0%E5%89%A9%E4%BD%99%E9%87%91%E9%A2%9D%0A%20%20%20%20while%20amt%20%3E%200%3A%0A%20%20%20%20%20%20%20%20%23%20%E6%89%BE%E5%88%B0%E4%B8%8D%E8%B6%85%E8%BF%87%E5%89%A9%E4%BD%99%E9%87%91%E9%A2%9D%E7%9A%84%E6%9C%80%E5%A4%A7%E9%9D%A2%E9%A2%9D%0A%20%20%20%20%20%20%20%20while%20i%20%3E%200%20and%20coins%5Bi%5D%20%3E%20amt%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20i%20-%3D%201%0A%20%20%20%20%20%20%20%20%23%20%E9%80%89%E6%8B%A9%20coins%5Bi%5D%0A%20%20%20%20%20%20%20%20amt%20-%3D%20coins%5Bi%5D%0A%20%20%20%20%20%20%20%20count%20%2B%3D%201%0A%20%20%20%20%23%20%E8%8B%A5%E6%9C%AA%E6%89%BE%E5%88%B0%E5%8F%AF%E8%A1%8C%E6%96%B9%E6%A1%88%EF%BC%8C%E5%88%99%E8%BF%94%E5%9B%9E%20-1%0A%20%20%20%20return%20count%20if%20amt%20%3D%3D%200%20else%20-1%0A%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E8%B4%AA%E5%BF%83%EF%BC%9A%E8%83%BD%E5%A4%9F%E4%BF%9D%E8%AF%81%E6%89%BE%E5%88%B0%E5%85%A8%E5%B1%80%E6%9C%80%E4%BC%98%E8%A7%A3%0A%20%20%20%20coins%20%3D%20%5B1,%205,%2010,%2020,%2050,%20100%5D%0A%20%20%20%20amt%20%3D%20186%0A%20%20%20%20res%20%3D%20coin_change_greedy%28coins,%20amt%29%0A%20%20%20%20print%28f%22%5Cncoins%20%3D%20%7Bcoins%7D,%20amt%20%3D%20%7Bamt%7D%22%29%0A%20%20%20%20print%28f%22%E5%87%91%E5%88%B0%20%7Bamt%7D%20%E6%89%80%E9%9C%80%E7%9A%84%E6%9C%80%E5%B0%91%E7%A1%AC%E5%B8%81%E6%95%B0%E9%87%8F%E4%B8%BA%20%7Bres%7D%22%29%0A%0A%20%20%20%20%23%20%E8%B4%AA%E5%BF%83%EF%BC%9A%E6%97%A0%E6%B3%95%E4%BF%9D%E8%AF%81%E6%89%BE%E5%88%B0%E5%85%A8%E5%B1%80%E6%9C%80%E4%BC%98%E8%A7%A3%0A%20%20%20%20coins%20%3D%20%5B1,%2020,%2050%5D%0A%20%20%20%20amt%20%3D%2060%0A%20%20%20%20res%20%3D%20coin_change_greedy%28coins,%20amt%29%0A%20%20%20%20print%28f%22%5Cncoins%20%3D%20%7Bcoins%7D,%20amt%20%3D%20%7Bamt%7D%22%29%0A%20%20%20%20print%28f%22%E5%87%91%E5%88%B0%20%7Bamt%7D%20%E6%89%80%E9%9C%80%E7%9A%84%E6%9C%80%E5%B0%91%E7%A1%AC%E5%B8%81%E6%95%B0%E9%87%8F%E4%B8%BA%20%7Bres%7D%22%29%0A%20%20%20%20print%28f%22%E5%AE%9E%E9%99%85%E4%B8%8A%E9%9C%80%E8%A6%81%E7%9A%84%E6%9C%80%E5%B0%91%E6%95%B0%E9%87%8F%E4%B8%BA%203%20%EF%BC%8C%E5%8D%B3%2020%20%2B%2020%20%2B%2020%22%29&cumulative=false&curInstr=5&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
|
||||
|
||||
@@ -11,7 +11,7 @@ def coin_change_greedy(coins, amt)
|
||||
count = 0
|
||||
# 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0
|
||||
# 找到小于且最接近剩余金额的硬币
|
||||
# 找到不超过剩余金额的最大面额
|
||||
while i > 0 && coins[i] > amt
|
||||
i -= 1
|
||||
end
|
||||
|
||||
@@ -47,8 +47,8 @@ fn build_tree(preorder: &[i32], inorder: &[i32]) -> Option<Rc<RefCell<TreeNode>>
|
||||
fn main() {
|
||||
let preorder = [3, 9, 2, 1, 7];
|
||||
let inorder = [9, 3, 1, 2, 7];
|
||||
println!("中序遍历 = {:?}", preorder);
|
||||
println!("前序遍历 = {:?}", inorder);
|
||||
println!("前序遍历 = {:?}", preorder);
|
||||
println!("中序遍历 = {:?}", inorder);
|
||||
|
||||
let root = build_tree(&preorder, &inorder);
|
||||
println!("构建的二叉树为:");
|
||||
|
||||
@@ -11,7 +11,7 @@ fn coin_change_greedy(coins: &[i32], mut amt: i32) -> i32 {
|
||||
let mut count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0 {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while i > 0 && coins[i] > amt {
|
||||
i -= 1;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
|
||||
var amt = amt
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0 {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while i > 0 && coins[i] > amt {
|
||||
i -= 1
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ function coinChangeGreedy(coins: number[], amt: number): number {
|
||||
let count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
// 找到不超过剩余金额的最大面额
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 73 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 61 KiB |
@@ -138,7 +138,7 @@ $$
|
||||
|
||||
进一步思考,我们能否仅用一个数组实现空间优化呢?观察可知,每个状态都是由正上方或左上方的格子转移过来的。假设只有一个数组,当开始遍历第 $i$ 行时,该数组存储的仍然是第 $i-1$ 行的状态。
|
||||
|
||||
- 如果采取正序遍历,那么遍历到 $dp[i, j]$ 时,左上方 $dp[i-1, 1]$ ~ $dp[i-1, j-1]$ 值可能已经被覆盖,此时就无法得到正确的状态转移结果。
|
||||
- 按容量从小到大更新时,计算 $dp[i, c]$ 所需的上一行状态 $dp[i-1, c-wgt[i-1]]$ 可能已被当前行覆盖,使同一件物品被重复计入。
|
||||
- 如果采取倒序遍历,则不会发生覆盖问题,状态转移可以正确进行。
|
||||
|
||||
下图展示了在单个数组下从第 $i = 1$ 行转换至第 $i = 2$ 行的过程。请思考正序遍历和倒序遍历的区别。
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"给定 5 件物品与背包容量 cap = 50,物品数据见下表。每件最多取其全部重量,也可以任意切分,只取一部分;所获价值按所取重量占原重量的比例计算。"
|
||||
],
|
||||
"description": [
|
||||
"画面左侧列出编号 i、重量 wgt[i-1]、价值 val[i-1],各行用水果图标标识物品。第 2 行香蕉和第 4 行菠萝以浅橙色突出,两条箭头分别标“放入重量 20”“放入重量 30”,指向右侧标有“背包容量 cap = 50”的背包。底部给出最优方案及最大价值算式。",
|
||||
"图左列出编号 i、重量 wgt[i-1] 和价值 val[i-1],各行以水果图标表示物品。第 2 行的香蕉为浅粉色,第 4 行的菠萝为浅橙色。“放入重量”一列分别写着 20 和 30,各有一支箭头从该行指向右侧容量为 50 的背包。图下方列出最优方案和最大价值的计算式。",
|
||||
"下表前三列转写原图,水果名称来自图标;额外的“单位价值”列由价值除以重量算出,原图未画这一列。例如苹果的单位价值为 50 ÷ 10 = 5。"
|
||||
],
|
||||
"frames": [
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
细心的读者可能发现了,**如果输入数据是对象,上述步骤 `3.` 就失效了**。假设输入数据是商品对象,我们想按照商品价格(类的成员变量)对商品进行排序,而上述算法只能给出价格的排序结果。
|
||||
|
||||
那么如何才能得到原数据的排序结果呢?我们首先计算 `counter` 的“前缀和”。顾名思义,索引 `i` 处的前缀和 `prefix[i]` 等于数组前 `i` 个元素之和:
|
||||
那么如何才能得到原数据的排序结果呢?我们首先计算 `counter` 的“前缀和”。顾名思义,索引 `i` 处的前缀和 `prefix[i]` 等于数组前 `i + 1` 个元素之和:
|
||||
|
||||
$$
|
||||
\text{prefix}[i] = \sum_{j=0}^i \text{counter[j]}
|
||||
|
||||
142
docs/index.html
142
docs/index.html
@@ -1,5 +1,5 @@
|
||||
<!-- Generated from the shared homepage template and locale configuration. -->
|
||||
<link href="assets/home/bf55006c61fda74c/hero-motion.css" rel="stylesheet"/>
|
||||
<link href="assets/home/1c170a18679bd6f8/hero-motion.css" rel="stylesheet"/>
|
||||
<noscript>
|
||||
<style>
|
||||
[data-home-src], video[data-home-poster], [data-hero-fallback] { display: none; }
|
||||
@@ -11,125 +11,125 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="hero-div" data-home-layout="universe">
|
||||
<img alt="" data-hero-asset="ground" data-source-height="380" data-source-width="881" height="380" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/567306c070a6a7e2/ground.webp" style="position: absolute; width: auto; height: 26.445%; left: 28.211%; top: 54.145%;; aspect-ratio: 881 / 380" width="881"/>
|
||||
<img alt="" data-hero-asset="ground" data-source-height="380" data-source-width="881" height="380" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/567306c070a6a7e2/ground.webp" style="position: absolute; width: auto; height: 26.445%; left: 28.211%; top: 54.145%;; aspect-ratio: 881 / 380" width="881"/>
|
||||
<a href="chapter_introduction/">
|
||||
<img alt="" data-hero-asset="astronaut" data-source-height="672" data-source-width="515" height="672" src="assets/home/bf55006c61fda74c/../shared/images/8e5eb3b3e3ebd9f7/astronaut.webp" style="height: 46.673%; left: 35.413%; top: 24.343%;; aspect-ratio: 515 / 672" width="515"/>
|
||||
<img alt="" data-hero-asset="astronaut" data-source-height="672" data-source-width="515" height="672" src="assets/home/1c170a18679bd6f8/../shared/images/8e5eb3b3e3ebd9f7/astronaut.webp" style="height: 46.673%; left: 35.413%; top: 24.343%;; aspect-ratio: 515 / 672" width="515"/>
|
||||
<span style="left: 52.244%; top: 20.919%;">
|
||||
初识算法
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_computational_complexity/">
|
||||
<img alt="" data-hero-asset="chapter_computational_complexity" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/2fb425426d1f8d86/chapter_computational_complexity.webp" data-source-height="178" data-source-width="113" height="178" style="height: 12.347%; left: 36.267%; top: 37.653%;; aspect-ratio: 113 / 178" width="113"/>
|
||||
<img alt="" data-hero-asset="chapter_computational_complexity" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/2fb425426d1f8d86/chapter_computational_complexity.webp" data-source-height="178" data-source-width="113" height="178" style="height: 12.347%; left: 36.267%; top: 37.653%;; aspect-ratio: 113 / 178" width="113"/>
|
||||
<noscript>
|
||||
<img alt="" height="178" src="assets/home/bf55006c61fda74c/../shared/images/2fb425426d1f8d86/chapter_computational_complexity.webp" style="height: 12.347%; left: 36.267%; top: 37.653%;" width="113"/>
|
||||
<img alt="" height="178" src="assets/home/1c170a18679bd6f8/../shared/images/2fb425426d1f8d86/chapter_computational_complexity.webp" style="height: 12.347%; left: 36.267%; top: 37.653%;" width="113"/>
|
||||
</noscript>
|
||||
<span style="left: 39.244%; top: 33.919%;">
|
||||
复杂度分析
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_array_and_linkedlist/">
|
||||
<img alt="" data-hero-asset="chapter_array_and_linkedlist" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/5cbbdf7be555d3ef/chapter_array_and_linkedlist.webp" data-source-height="319" data-source-width="468" height="319" style="height: 22.242%; left: 73.242%; top: 52.481%;; aspect-ratio: 468 / 319" width="468"/>
|
||||
<img alt="" data-hero-asset="chapter_array_and_linkedlist" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/5cbbdf7be555d3ef/chapter_array_and_linkedlist.webp" data-source-height="319" data-source-width="468" height="319" style="height: 22.242%; left: 73.242%; top: 52.481%;; aspect-ratio: 468 / 319" width="468"/>
|
||||
<noscript>
|
||||
<img alt="" height="319" src="assets/home/bf55006c61fda74c/../shared/images/5cbbdf7be555d3ef/chapter_array_and_linkedlist.webp" style="height: 22.242%; left: 73.242%; top: 52.481%;" width="468"/>
|
||||
<img alt="" height="319" src="assets/home/1c170a18679bd6f8/../shared/images/5cbbdf7be555d3ef/chapter_array_and_linkedlist.webp" style="height: 22.242%; left: 73.242%; top: 52.481%;" width="468"/>
|
||||
</noscript>
|
||||
<span style="left: 90.897%; top: 76.259%;">
|
||||
数组与链表
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_stack_and_queue/">
|
||||
<img alt="" data-hero-asset="chapter_stack_and_queue" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/e2667767cf7481bd/chapter_stack_and_queue.webp" data-source-height="204" data-source-width="204" height="204" style="height: 14.302%; left: 62.646%; top: 77.875%;; aspect-ratio: 204 / 204" width="204"/>
|
||||
<img alt="" data-hero-asset="chapter_stack_and_queue" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/e2667767cf7481bd/chapter_stack_and_queue.webp" data-source-height="204" data-source-width="204" height="204" style="height: 14.302%; left: 62.646%; top: 77.875%;; aspect-ratio: 204 / 204" width="204"/>
|
||||
<noscript>
|
||||
<img alt="" height="204" src="assets/home/bf55006c61fda74c/../shared/images/e2667767cf7481bd/chapter_stack_and_queue.webp" style="height: 14.302%; left: 62.646%; top: 77.875%;" width="204"/>
|
||||
<img alt="" height="204" src="assets/home/1c170a18679bd6f8/../shared/images/e2667767cf7481bd/chapter_stack_and_queue.webp" style="height: 14.302%; left: 62.646%; top: 77.875%;" width="204"/>
|
||||
</noscript>
|
||||
<span style="left: 77.571%; top: 91.25%;">
|
||||
栈与队列
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_hashing/">
|
||||
<img alt="" data-hero-asset="chapter_hashing" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/b108d70a537714cb/chapter_hashing.webp" data-source-height="218" data-source-width="218" height="218" style="height: 15.266%; left: 63.281%; top: 27.933%;; aspect-ratio: 218 / 218" width="218"/>
|
||||
<img alt="" data-hero-asset="chapter_hashing" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/b108d70a537714cb/chapter_hashing.webp" data-source-height="218" data-source-width="218" height="218" style="height: 15.266%; left: 63.281%; top: 27.933%;; aspect-ratio: 218 / 218" width="218"/>
|
||||
<noscript>
|
||||
<img alt="" height="218" src="assets/home/bf55006c61fda74c/../shared/images/b108d70a537714cb/chapter_hashing.webp" style="height: 15.266%; left: 63.281%; top: 27.933%;" width="218"/>
|
||||
<img alt="" height="218" src="assets/home/1c170a18679bd6f8/../shared/images/b108d70a537714cb/chapter_hashing.webp" style="height: 15.266%; left: 63.281%; top: 27.933%;" width="218"/>
|
||||
</noscript>
|
||||
<span style="left: 68.862%; top: 46.292%;">
|
||||
哈希表
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_tree/">
|
||||
<img alt="" data-hero-asset="chapter_tree" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/8138bb0acecedec4/chapter_tree.webp" data-source-height="281" data-source-width="280" height="281" style="height: 19.615%; left: 80.137%; top: 26.678%;; aspect-ratio: 280 / 281" width="280"/>
|
||||
<img alt="" data-hero-asset="chapter_tree" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/8138bb0acecedec4/chapter_tree.webp" data-source-height="281" data-source-width="280" height="281" style="height: 19.615%; left: 80.137%; top: 26.678%;; aspect-ratio: 280 / 281" width="280"/>
|
||||
<noscript>
|
||||
<img alt="" height="281" src="assets/home/bf55006c61fda74c/../shared/images/8138bb0acecedec4/chapter_tree.webp" style="height: 19.615%; left: 80.137%; top: 26.678%;" width="280"/>
|
||||
<img alt="" height="281" src="assets/home/1c170a18679bd6f8/../shared/images/8138bb0acecedec4/chapter_tree.webp" style="height: 19.615%; left: 80.137%; top: 26.678%;" width="280"/>
|
||||
</noscript>
|
||||
<span style="left: 96.159%; top: 44.8%;">
|
||||
树
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_heap/">
|
||||
<img alt="" data-hero-asset="chapter_heap" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/7586281e6691807a/chapter_heap.webp" data-source-height="152" data-source-width="151" height="152" style="height: 10.566%; left: 77.226%; top: 11.559%;; aspect-ratio: 151 / 152" width="151"/>
|
||||
<img alt="" data-hero-asset="chapter_heap" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/7586281e6691807a/chapter_heap.webp" data-source-height="152" data-source-width="151" height="152" style="height: 10.566%; left: 77.226%; top: 11.559%;; aspect-ratio: 151 / 152" width="151"/>
|
||||
<noscript>
|
||||
<img alt="" height="152" src="assets/home/bf55006c61fda74c/../shared/images/7586281e6691807a/chapter_heap.webp" style="height: 10.566%; left: 77.226%; top: 11.559%;" width="151"/>
|
||||
<img alt="" height="152" src="assets/home/1c170a18679bd6f8/../shared/images/7586281e6691807a/chapter_heap.webp" style="height: 10.566%; left: 77.226%; top: 11.559%;" width="151"/>
|
||||
</noscript>
|
||||
<span style="left: 88.103%; top: 15.422%;">
|
||||
堆
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_graph/">
|
||||
<img alt="" data-hero-asset="chapter_graph" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/175a7f2e7c3cf5f0/chapter_graph.webp" data-source-height="272" data-source-width="542" height="272" style="height: 16.112%; left: 51.854%; top: 5.575%;; aspect-ratio: 542 / 272" width="542"/>
|
||||
<img alt="" data-hero-asset="chapter_graph" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/175a7f2e7c3cf5f0/chapter_graph.webp" data-source-height="272" data-source-width="542" height="272" style="height: 16.112%; left: 51.854%; top: 5.575%;; aspect-ratio: 542 / 272" width="542"/>
|
||||
<noscript>
|
||||
<img alt="" height="272" src="assets/home/bf55006c61fda74c/../shared/images/175a7f2e7c3cf5f0/chapter_graph.webp" style="height: 16.112%; left: 51.854%; top: 5.575%;" width="542"/>
|
||||
<img alt="" height="272" src="assets/home/1c170a18679bd6f8/../shared/images/175a7f2e7c3cf5f0/chapter_graph.webp" style="height: 16.112%; left: 51.854%; top: 5.575%;" width="542"/>
|
||||
</noscript>
|
||||
<span style="left: 71.195%; top: 6.503%;">
|
||||
图
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_searching/">
|
||||
<img alt="" data-hero-asset="chapter_searching" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/ebfe2b953dbb9d90/chapter_searching.webp" data-source-height="216" data-source-width="216" height="216" style="height: 15.149%; left: 18.185%; top: 16.404%;; aspect-ratio: 216 / 216" width="216"/>
|
||||
<img alt="" data-hero-asset="chapter_searching" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/ebfe2b953dbb9d90/chapter_searching.webp" data-source-height="216" data-source-width="216" height="216" style="height: 15.149%; left: 18.185%; top: 16.404%;; aspect-ratio: 216 / 216" width="216"/>
|
||||
<noscript>
|
||||
<img alt="" height="216" src="assets/home/bf55006c61fda74c/../shared/images/ebfe2b953dbb9d90/chapter_searching.webp" style="height: 15.149%; left: 18.185%; top: 16.404%;" width="216"/>
|
||||
<img alt="" height="216" src="assets/home/1c170a18679bd6f8/../shared/images/ebfe2b953dbb9d90/chapter_searching.webp" style="height: 15.149%; left: 18.185%; top: 16.404%;" width="216"/>
|
||||
</noscript>
|
||||
<span style="left: 14.556%; top: 20.876%;">
|
||||
搜索
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_sorting/">
|
||||
<img alt="" data-hero-asset="chapter_sorting" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/9d4be68b2680967c/chapter_sorting.webp" data-source-height="137" data-source-width="138" height="137" style="height: 9.574%; left: 25.409%; top: 40.747%;; aspect-ratio: 138 / 137" width="138"/>
|
||||
<img alt="" data-hero-asset="chapter_sorting" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/9d4be68b2680967c/chapter_sorting.webp" data-source-height="137" data-source-width="138" height="137" style="height: 9.574%; left: 25.409%; top: 40.747%;; aspect-ratio: 138 / 137" width="138"/>
|
||||
<noscript>
|
||||
<img alt="" height="137" src="assets/home/bf55006c61fda74c/../shared/images/9d4be68b2680967c/chapter_sorting.webp" style="height: 9.574%; left: 25.409%; top: 40.747%;" width="138"/>
|
||||
<img alt="" height="137" src="assets/home/1c170a18679bd6f8/../shared/images/9d4be68b2680967c/chapter_sorting.webp" style="height: 9.574%; left: 25.409%; top: 40.747%;" width="138"/>
|
||||
</noscript>
|
||||
<span style="left: 28.805%; top: 53.808%;">
|
||||
排序
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_divide_and_conquer/">
|
||||
<img alt="" data-hero-asset="chapter_divide_and_conquer" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/6f5766ca9385cd2e/chapter_divide_and_conquer.webp" data-source-height="269" data-source-width="407" height="269" style="height: 18.681%; left: 32.721%; top: 4.816%;; aspect-ratio: 407 / 269" width="407"/>
|
||||
<img alt="" data-hero-asset="chapter_divide_and_conquer" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/6f5766ca9385cd2e/chapter_divide_and_conquer.webp" data-source-height="269" data-source-width="407" height="269" style="height: 18.681%; left: 32.721%; top: 4.816%;; aspect-ratio: 407 / 269" width="407"/>
|
||||
<noscript>
|
||||
<img alt="" height="269" src="assets/home/bf55006c61fda74c/../shared/images/6f5766ca9385cd2e/chapter_divide_and_conquer.webp" style="height: 18.681%; left: 32.721%; top: 4.816%;" width="407"/>
|
||||
<img alt="" height="269" src="assets/home/1c170a18679bd6f8/../shared/images/6f5766ca9385cd2e/chapter_divide_and_conquer.webp" style="height: 18.681%; left: 32.721%; top: 4.816%;" width="407"/>
|
||||
</noscript>
|
||||
<span style="left: 31.42%; top: 8.679%;">
|
||||
分治
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_backtracking/">
|
||||
<img alt="" data-hero-asset="chapter_backtracking" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/176675e685febf11/chapter_backtracking.webp" data-source-height="249" data-source-width="345" height="249" style="height: 17.338%; left: 4.875%; top: 32.925%;; aspect-ratio: 345 / 249" width="345"/>
|
||||
<img alt="" data-hero-asset="chapter_backtracking" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/176675e685febf11/chapter_backtracking.webp" data-source-height="249" data-source-width="345" height="249" style="height: 17.338%; left: 4.875%; top: 32.925%;; aspect-ratio: 345 / 249" width="345"/>
|
||||
<noscript>
|
||||
<img alt="" height="249" src="assets/home/bf55006c61fda74c/../shared/images/176675e685febf11/chapter_backtracking.webp" style="height: 17.338%; left: 4.875%; top: 32.925%;" width="345"/>
|
||||
<img alt="" height="249" src="assets/home/1c170a18679bd6f8/../shared/images/176675e685febf11/chapter_backtracking.webp" style="height: 17.338%; left: 4.875%; top: 32.925%;" width="345"/>
|
||||
</noscript>
|
||||
<span style="left: 4.742%; top: 50.113%;">
|
||||
回溯
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_dynamic_programming/">
|
||||
<img alt="" data-hero-asset="chapter_dynamic_programming" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/06264b1ffd05b08e/chapter_dynamic_programming.webp" data-source-height="268" data-source-width="267" height="268" style="height: 15.47%; left: 9.406%; top: 57.472%;; aspect-ratio: 267 / 268" width="267"/>
|
||||
<img alt="" data-hero-asset="chapter_dynamic_programming" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/06264b1ffd05b08e/chapter_dynamic_programming.webp" data-source-height="268" data-source-width="267" height="268" style="height: 15.47%; left: 9.406%; top: 57.472%;; aspect-ratio: 267 / 268" width="267"/>
|
||||
<noscript>
|
||||
<img alt="" height="268" src="assets/home/bf55006c61fda74c/../shared/images/06264b1ffd05b08e/chapter_dynamic_programming.webp" style="height: 15.47%; left: 9.406%; top: 57.472%;" width="267"/>
|
||||
<img alt="" height="268" src="assets/home/1c170a18679bd6f8/../shared/images/06264b1ffd05b08e/chapter_dynamic_programming.webp" style="height: 15.47%; left: 9.406%; top: 57.472%;" width="267"/>
|
||||
</noscript>
|
||||
<span style="left: 8.561%; top: 75.351%;">
|
||||
动态规划
|
||||
</span>
|
||||
</a>
|
||||
<a href="chapter_greedy/">
|
||||
<img alt="" data-hero-asset="chapter_greedy" data-hero-fallback="assets/home/bf55006c61fda74c/../shared/images/2ce6caaac951c40b/chapter_greedy.webp" data-source-height="202" data-source-width="265" height="202" style="height: 14.127%; left: 23.132%; top: 75.803%;; aspect-ratio: 265 / 202" width="265"/>
|
||||
<img alt="" data-hero-asset="chapter_greedy" data-hero-fallback="assets/home/1c170a18679bd6f8/../shared/images/2ce6caaac951c40b/chapter_greedy.webp" data-source-height="202" data-source-width="265" height="202" style="height: 14.127%; left: 23.132%; top: 75.803%;; aspect-ratio: 265 / 202" width="265"/>
|
||||
<noscript>
|
||||
<img alt="" height="202" src="assets/home/bf55006c61fda74c/../shared/images/2ce6caaac951c40b/chapter_greedy.webp" style="height: 14.127%; left: 23.132%; top: 75.803%;" width="265"/>
|
||||
<img alt="" height="202" src="assets/home/1c170a18679bd6f8/../shared/images/2ce6caaac951c40b/chapter_greedy.webp" style="height: 14.127%; left: 23.132%; top: 75.803%;" width="265"/>
|
||||
</noscript>
|
||||
<span style="left: 21.619%; top: 86.85%;">
|
||||
贪心
|
||||
@@ -177,9 +177,9 @@
|
||||
<a href="chapter_paperbook/">
|
||||
<div style="height: 8.17%;">
|
||||
</div>
|
||||
<img alt="Cover" class="device-on-hover" data-home-src="assets/home/bf55006c61fda74c/../shared/images/dc5be783cea3a262/cover_render.webp" decoding="async" height="720" style="height: 66.83%;" width="535"/>
|
||||
<img alt="Cover" class="device-on-hover" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/dc5be783cea3a262/cover_render.webp" decoding="async" height="720" style="height: 66.83%;" width="535"/>
|
||||
<noscript>
|
||||
<img alt="Cover" class="device-on-hover" height="720" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/dc5be783cea3a262/cover_render.webp" style="height: 66.83%;" width="535"/>
|
||||
<img alt="Cover" class="device-on-hover" height="720" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/dc5be783cea3a262/cover_render.webp" style="height: 66.83%;" width="535"/>
|
||||
</noscript>
|
||||
<div class="text-button">
|
||||
<span>
|
||||
@@ -196,9 +196,9 @@
|
||||
<a href="chapter_hello_algo/">
|
||||
<div style="height: 4.34%;">
|
||||
</div>
|
||||
<img alt="" class="device-on-hover" data-home-src="assets/home/bf55006c61fda74c/../shared/images/5b64cf7672ec5ec6/web_mac_iphone.webp" decoding="async" height="965" style="height: 66.31%;" width="1598"/>
|
||||
<img alt="" class="device-on-hover" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/5b64cf7672ec5ec6/web_mac_iphone.webp" decoding="async" height="965" style="height: 66.31%;" width="1598"/>
|
||||
<noscript>
|
||||
<img alt="" class="device-on-hover" height="965" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/5b64cf7672ec5ec6/web_mac_iphone.webp" style="height: 66.31%;" width="1598"/>
|
||||
<img alt="" class="device-on-hover" height="965" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/5b64cf7672ec5ec6/web_mac_iphone.webp" style="height: 66.31%;" width="1598"/>
|
||||
</noscript>
|
||||
<div style="height: 4.34%;">
|
||||
</div>
|
||||
@@ -215,9 +215,9 @@
|
||||
</div>
|
||||
<div class="media-block">
|
||||
<a href="https://github.com/krahets/hello-algo/releases">
|
||||
<img alt="" class="device-on-hover" data-home-src="assets/home/bf55006c61fda74c/../shared/images/66baa2f9bf3abec7/pdf_ipad.webp" decoding="async" height="960" style="height: 75%;" width="812"/>
|
||||
<img alt="" class="device-on-hover" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/66baa2f9bf3abec7/pdf_ipad.webp" decoding="async" height="960" style="height: 75%;" width="812"/>
|
||||
<noscript>
|
||||
<img alt="" class="device-on-hover" height="960" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/66baa2f9bf3abec7/pdf_ipad.webp" style="height: 75%;" width="812"/>
|
||||
<img alt="" class="device-on-hover" height="960" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/66baa2f9bf3abec7/pdf_ipad.webp" style="height: 75%;" width="812"/>
|
||||
</noscript>
|
||||
<div class="text-button">
|
||||
<span>
|
||||
@@ -285,21 +285,21 @@
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<video aria-label="Animation example" class="intro-image" data-home-poster="assets/home/bf55006c61fda74c/../shared/images/9e5f39bf33afc70f/animation-poster.webp" data-home-video="assets/home/bf55006c61fda74c/../shared/media/6c70de2b2bf4eef7/animation.mp4" height="1080" loop="" muted="" playsinline="" preload="none" style="aspect-ratio: 1600 / 1080" width="1600">
|
||||
<video aria-label="Animation example" class="intro-image" data-home-poster="assets/home/1c170a18679bd6f8/../shared/images/9e5f39bf33afc70f/animation-poster.webp" data-home-video="assets/home/1c170a18679bd6f8/../shared/media/6c70de2b2bf4eef7/animation.mp4" height="1080" loop="" muted="" playsinline="" preload="none" style="aspect-ratio: 1600 / 1080" width="1600">
|
||||
</video>
|
||||
<noscript>
|
||||
<a href="assets/home/bf55006c61fda74c/../shared/media/6c70de2b2bf4eef7/animation.mp4">
|
||||
<img alt="Animation example" class="intro-image" height="1080" src="assets/home/bf55006c61fda74c/../shared/images/9e5f39bf33afc70f/animation-poster.webp" width="1600"/>
|
||||
<a href="assets/home/1c170a18679bd6f8/../shared/media/6c70de2b2bf4eef7/animation.mp4">
|
||||
<img alt="Animation example" class="intro-image" height="1080" src="assets/home/1c170a18679bd6f8/../shared/images/9e5f39bf33afc70f/animation-poster.webp" width="1600"/>
|
||||
动画图解
|
||||
</a>
|
||||
</noscript>
|
||||
</div>
|
||||
<div class="intro-container">
|
||||
<video aria-label="Running code example" class="intro-image" data-home-poster="assets/home/bf55006c61fda74c/../shared/images/f33a13e8331245ae/running_code-poster.webp" data-home-video="assets/home/bf55006c61fda74c/../shared/media/bb169a96ca8316da/running_code.mp4" height="1082" loop="" muted="" playsinline="" preload="none" style="aspect-ratio: 1600 / 1082" width="1600">
|
||||
<video aria-label="Running code example" class="intro-image" data-home-poster="assets/home/1c170a18679bd6f8/../shared/images/f33a13e8331245ae/running_code-poster.webp" data-home-video="assets/home/1c170a18679bd6f8/../shared/media/bb169a96ca8316da/running_code.mp4" height="1082" loop="" muted="" playsinline="" preload="none" style="aspect-ratio: 1600 / 1082" width="1600">
|
||||
</video>
|
||||
<noscript>
|
||||
<a href="assets/home/bf55006c61fda74c/../shared/media/bb169a96ca8316da/running_code.mp4">
|
||||
<img alt="Running code example" class="intro-image" height="1082" src="assets/home/bf55006c61fda74c/../shared/images/f33a13e8331245ae/running_code-poster.webp" width="1600"/>
|
||||
<a href="assets/home/1c170a18679bd6f8/../shared/media/bb169a96ca8316da/running_code.mp4">
|
||||
<img alt="Running code example" class="intro-image" height="1082" src="assets/home/1c170a18679bd6f8/../shared/images/f33a13e8331245ae/running_code-poster.webp" width="1600"/>
|
||||
一键运行
|
||||
</a>
|
||||
</noscript>
|
||||
@@ -347,11 +347,11 @@
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<video aria-label="Comments example" class="intro-image" data-home-poster="assets/home/bf55006c61fda74c/../shared/images/f9ac69536a7582f5/comment-poster.webp" data-home-video="assets/home/bf55006c61fda74c/../shared/media/62aa0b8d351c63a7/comment.mp4" height="1080" loop="" muted="" playsinline="" preload="none" style="aspect-ratio: 1600 / 1080" width="1600">
|
||||
<video aria-label="Comments example" class="intro-image" data-home-poster="assets/home/1c170a18679bd6f8/../shared/images/f9ac69536a7582f5/comment-poster.webp" data-home-video="assets/home/1c170a18679bd6f8/../shared/media/62aa0b8d351c63a7/comment.mp4" height="1080" loop="" muted="" playsinline="" preload="none" style="aspect-ratio: 1600 / 1080" width="1600">
|
||||
</video>
|
||||
<noscript>
|
||||
<a href="assets/home/bf55006c61fda74c/../shared/media/62aa0b8d351c63a7/comment.mp4">
|
||||
<img alt="Comments example" class="intro-image" height="1080" src="assets/home/bf55006c61fda74c/../shared/images/f9ac69536a7582f5/comment-poster.webp" width="1600"/>
|
||||
<a href="assets/home/1c170a18679bd6f8/../shared/media/62aa0b8d351c63a7/comment.mp4">
|
||||
<img alt="Comments example" class="intro-image" height="1080" src="assets/home/1c170a18679bd6f8/../shared/images/f9ac69536a7582f5/comment-poster.webp" width="1600"/>
|
||||
互助学习
|
||||
</a>
|
||||
</noscript>
|
||||
@@ -367,9 +367,9 @@
|
||||
<div class="profile-div">
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/krahets">
|
||||
<img alt="Author: yudongjin" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/02348410d40f7665/avatar_yudongjin.webp" decoding="async" height="512" width="512"/>
|
||||
<img alt="Author: yudongjin" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/02348410d40f7665/avatar_yudongjin.webp" decoding="async" height="512" width="512"/>
|
||||
<noscript>
|
||||
<img alt="Author: yudongjin" class="profile-img" height="512" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/02348410d40f7665/avatar_yudongjin.webp" width="512"/>
|
||||
<img alt="Author: yudongjin" class="profile-img" height="512" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/02348410d40f7665/avatar_yudongjin.webp" width="512"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -389,9 +389,9 @@
|
||||
<div class="profile-div">
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/coderonion">
|
||||
<img alt="Reviewer: coderonion" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/db606f27971eae34/avatar_coderonion.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: coderonion" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/db606f27971eae34/avatar_coderonion.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: coderonion" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/db606f27971eae34/avatar_coderonion.webp" width="384"/>
|
||||
<img alt="Reviewer: coderonion" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/db606f27971eae34/avatar_coderonion.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -405,9 +405,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/curtishd">
|
||||
<img alt="Reviewer: curtishd" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/feedb0e547ea31fc/avatar_curtishd.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: curtishd" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/feedb0e547ea31fc/avatar_curtishd.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: curtishd" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/feedb0e547ea31fc/avatar_curtishd.webp" width="384"/>
|
||||
<img alt="Reviewer: curtishd" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/feedb0e547ea31fc/avatar_curtishd.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -421,9 +421,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/Gonglja">
|
||||
<img alt="Reviewer: Gonglja" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/cdcf023b032b8d30/avatar_Gonglja.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: Gonglja" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/cdcf023b032b8d30/avatar_Gonglja.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: Gonglja" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/cdcf023b032b8d30/avatar_Gonglja.webp" width="384"/>
|
||||
<img alt="Reviewer: Gonglja" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/cdcf023b032b8d30/avatar_Gonglja.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -437,9 +437,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/gvenusleo">
|
||||
<img alt="Reviewer: gvenusleo" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/464e2d351b9263ec/avatar_gvenusleo.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: gvenusleo" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/464e2d351b9263ec/avatar_gvenusleo.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: gvenusleo" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/464e2d351b9263ec/avatar_gvenusleo.webp" width="384"/>
|
||||
<img alt="Reviewer: gvenusleo" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/464e2d351b9263ec/avatar_gvenusleo.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -453,9 +453,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/hpstory">
|
||||
<img alt="Reviewer: hpstory" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/7b6478acdab6b845/avatar_hpstory.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: hpstory" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/7b6478acdab6b845/avatar_hpstory.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: hpstory" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/7b6478acdab6b845/avatar_hpstory.webp" width="384"/>
|
||||
<img alt="Reviewer: hpstory" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/7b6478acdab6b845/avatar_hpstory.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -469,9 +469,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/justin-tse">
|
||||
<img alt="Reviewer: justin-tse" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/208ee5aae490eefa/avatar_justin-tse.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: justin-tse" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/208ee5aae490eefa/avatar_justin-tse.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: justin-tse" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/208ee5aae490eefa/avatar_justin-tse.webp" width="384"/>
|
||||
<img alt="Reviewer: justin-tse" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/208ee5aae490eefa/avatar_justin-tse.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -485,9 +485,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/khoaxuantu">
|
||||
<img alt="Reviewer: khoaxuantu" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/9d3f1a21ff51de78/avatar_khoaxuantu.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: khoaxuantu" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/9d3f1a21ff51de78/avatar_khoaxuantu.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: khoaxuantu" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/9d3f1a21ff51de78/avatar_khoaxuantu.webp" width="384"/>
|
||||
<img alt="Reviewer: khoaxuantu" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/9d3f1a21ff51de78/avatar_khoaxuantu.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -501,9 +501,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/krahets">
|
||||
<img alt="Reviewer: krahets" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/e321f9a3ac2739e0/avatar_krahets.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: krahets" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/e321f9a3ac2739e0/avatar_krahets.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: krahets" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/e321f9a3ac2739e0/avatar_krahets.webp" width="384"/>
|
||||
<img alt="Reviewer: krahets" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/e321f9a3ac2739e0/avatar_krahets.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -517,9 +517,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/night-cruise">
|
||||
<img alt="Reviewer: night-cruise" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/960b489efa22abd4/avatar_night-cruise.jpg" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: night-cruise" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/960b489efa22abd4/avatar_night-cruise.jpg" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: night-cruise" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/960b489efa22abd4/avatar_night-cruise.jpg" width="384"/>
|
||||
<img alt="Reviewer: night-cruise" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/960b489efa22abd4/avatar_night-cruise.jpg" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -533,9 +533,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/nuomi1">
|
||||
<img alt="Reviewer: nuomi1" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/7316a9eb4429b259/avatar_nuomi1.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: nuomi1" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/7316a9eb4429b259/avatar_nuomi1.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: nuomi1" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/7316a9eb4429b259/avatar_nuomi1.webp" width="384"/>
|
||||
<img alt="Reviewer: nuomi1" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/7316a9eb4429b259/avatar_nuomi1.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -549,9 +549,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/Reanon">
|
||||
<img alt="Reviewer: Reanon" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/dcc15aa68cc793c7/avatar_Reanon.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: Reanon" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/dcc15aa68cc793c7/avatar_Reanon.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: Reanon" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/dcc15aa68cc793c7/avatar_Reanon.webp" width="384"/>
|
||||
<img alt="Reviewer: Reanon" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/dcc15aa68cc793c7/avatar_Reanon.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -565,9 +565,9 @@
|
||||
</div>
|
||||
<div class="profile-cell">
|
||||
<a href="https://github.com/rongyi">
|
||||
<img alt="Reviewer: rongyi" class="profile-img" data-home-src="assets/home/bf55006c61fda74c/../shared/images/5dc6c4b1d8bfe0ac/avatar_rongyi.webp" decoding="async" height="384" width="384"/>
|
||||
<img alt="Reviewer: rongyi" class="profile-img" data-home-src="assets/home/1c170a18679bd6f8/../shared/images/5dc6c4b1d8bfe0ac/avatar_rongyi.webp" decoding="async" height="384" width="384"/>
|
||||
<noscript>
|
||||
<img alt="Reviewer: rongyi" class="profile-img" height="384" loading="lazy" src="assets/home/bf55006c61fda74c/../shared/images/5dc6c4b1d8bfe0ac/avatar_rongyi.webp" width="384"/>
|
||||
<img alt="Reviewer: rongyi" class="profile-img" height="384" loading="lazy" src="assets/home/1c170a18679bd6f8/../shared/images/5dc6c4b1d8bfe0ac/avatar_rongyi.webp" width="384"/>
|
||||
</noscript>
|
||||
<br/>
|
||||
<b>
|
||||
@@ -598,7 +598,7 @@
|
||||
</div>
|
||||
</section>
|
||||
<!-- This independent fallback also works when the deferred loader cannot be fetched. -->
|
||||
<script defer="" onerror="document.querySelectorAll('[data-home-src], [data-home-poster]').forEach(function(el) { if (el.dataset.homeSrc) el.src = el.dataset.homeSrc; if (el.dataset.homePoster) el.poster = el.dataset.homePoster; });" src="assets/home/bf55006c61fda74c/javascripts/homepage-media.js">
|
||||
<script defer="" onerror="document.querySelectorAll('[data-home-src], [data-home-poster]').forEach(function(el) { if (el.dataset.homeSrc) el.src = el.dataset.homeSrc; if (el.dataset.homePoster) el.poster = el.dataset.homePoster; });" src="assets/home/1c170a18679bd6f8/javascripts/homepage-media.js">
|
||||
</script>
|
||||
<script>
|
||||
// If the scene entry point itself fails, still provide chapter illustrations.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
FROM ubuntu:latest
|
||||
|
||||
# Use Aliyun mirrors for Ubuntu packages
|
||||
# Use the Aliyun mirrors for Ubuntu packages
|
||||
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
|
||||
sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
|
||||
sed -i 's/ports.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
|
||||
|
||||
RUN apt-get update && apt-get install -y wget
|
||||
|
||||
# Install the requested language environments
|
||||
# Install the selected language toolchains
|
||||
ARG LANGS
|
||||
RUN for LANG in $LANGS; do \
|
||||
case $LANG in \
|
||||
|
||||
6
en/codes/c/.gitignore
vendored
6
en/codes/c/.gitignore
vendored
@@ -1,8 +1,8 @@
|
||||
# Ignore all
|
||||
# Ignore everything
|
||||
*
|
||||
# Unignore all files with extensions
|
||||
# Include files with extensions
|
||||
!*.*
|
||||
# Unignore all directories
|
||||
# Include all directories
|
||||
!*/
|
||||
*.dSYM/
|
||||
|
||||
|
||||
@@ -6,45 +6,45 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Access an element at a random index */
|
||||
/* Access a random element */
|
||||
int randomAccess(int *nums, int size) {
|
||||
// Choose a random number in [0, size)
|
||||
// Pick a random index in [0, size)
|
||||
int randomIndex = rand() % size;
|
||||
// Get and return the randomly selected element
|
||||
// Get and return the element at that index
|
||||
int randomNum = nums[randomIndex];
|
||||
return randomNum;
|
||||
}
|
||||
|
||||
/* Extend the array length */
|
||||
/* Extend the array */
|
||||
int *extend(int *nums, int size, int enlarge) {
|
||||
// Initialize an array with the extended length
|
||||
// Initialize an array with the new length
|
||||
int *res = (int *)malloc(sizeof(int) * (size + enlarge));
|
||||
// Copy all elements from the original array to the new array
|
||||
// Copy all elements from the original array into the new array
|
||||
for (int i = 0; i < size; i++) {
|
||||
res[i] = nums[i];
|
||||
}
|
||||
// Initialize the newly added space
|
||||
// Initialize the extra space
|
||||
for (int i = size; i < size + enlarge; i++) {
|
||||
res[i] = 0;
|
||||
}
|
||||
// Return the new, extended array
|
||||
// Return the new, longer array
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Insert element num at index `index` in the array */
|
||||
/* Insert num at the specified array index */
|
||||
void insert(int *nums, int size, int num, int index) {
|
||||
// Shift all elements at and after index `index` one position to the right
|
||||
// Shift the elements from index onward one position to the right
|
||||
for (int i = size - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// Assign num to the element at index `index`
|
||||
// Store num at the specified index
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* Remove the element at index `index` */
|
||||
// Note: stdio.h already declares a function named remove
|
||||
/* Remove the element at the specified index */
|
||||
// Note: stdio.h already uses the name remove
|
||||
void removeItem(int *nums, int size, int index) {
|
||||
// Shift all elements after index `index` one position to the left
|
||||
// Shift all elements after index one position to the left
|
||||
for (int i = index; i < size - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
@@ -59,7 +59,7 @@ void traverse(int *nums, int size) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Find a specified element in the array */
|
||||
/* Find a given element in the array */
|
||||
int find(int *nums, int size, int target) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (nums[i] == target)
|
||||
@@ -68,7 +68,7 @@ int find(int *nums, int size, int target) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Initialize the random seed (only once) */
|
||||
srand((unsigned)time(NULL));
|
||||
@@ -85,23 +85,23 @@ int main() {
|
||||
|
||||
/* Random access */
|
||||
int randomNum = randomAccess(nums, size);
|
||||
printf("Random element selected from nums: %d", randomNum);
|
||||
printf("Random element from nums: %d", randomNum);
|
||||
|
||||
/* Extend the length */
|
||||
/* Extend the array */
|
||||
int enlarge = 3;
|
||||
int *res = extend(nums, size, enlarge);
|
||||
size += enlarge;
|
||||
printf("Extend the array length to 8, giving nums = ");
|
||||
printf("After extending the array to length 8, nums = ");
|
||||
printArray(res, size);
|
||||
|
||||
/* Insert an element */
|
||||
insert(res, size, 6, 3);
|
||||
printf("Insert the number 6 at index 3, giving nums = ");
|
||||
printf("After inserting 6 at index 3, nums = ");
|
||||
printArray(res, size);
|
||||
|
||||
/* Remove an element */
|
||||
removeItem(res, size, 2);
|
||||
printf("Remove the element at index 2, giving nums = ");
|
||||
printf("After removing the element at index 2, nums = ");
|
||||
printArray(res, size);
|
||||
|
||||
/* Traverse the array */
|
||||
@@ -109,7 +109,7 @@ int main() {
|
||||
|
||||
/* Find an element */
|
||||
int index = find(res, size, 3);
|
||||
printf("Find element 3 in res; its index = %d\n", index);
|
||||
printf("Index of 3 in res = %d\n", index);
|
||||
|
||||
/* Free memory */
|
||||
free(res);
|
||||
|
||||
@@ -13,8 +13,8 @@ void insert(ListNode *n0, ListNode *P) {
|
||||
n0->next = P;
|
||||
}
|
||||
|
||||
/* Remove the first node after node n0 in the linked list */
|
||||
// Note: stdio.h already declares a function named remove
|
||||
/* Remove the node immediately after n0 in the linked list */
|
||||
// Note: stdio.h already uses the name remove
|
||||
void removeItem(ListNode *n0) {
|
||||
if (!n0->next)
|
||||
return;
|
||||
@@ -26,7 +26,7 @@ void removeItem(ListNode *n0) {
|
||||
free(P);
|
||||
}
|
||||
|
||||
/* Access the node at index `index` in the linked list */
|
||||
/* Access the linked list node at the specified index */
|
||||
ListNode *access(ListNode *head, int index) {
|
||||
for (int i = 0; i < index; i++) {
|
||||
if (head == NULL)
|
||||
@@ -48,16 +48,16 @@ int find(ListNode *head, int target) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Initialize the linked list */
|
||||
// Initialize the individual nodes
|
||||
// Initialize the nodes
|
||||
ListNode *n0 = newListNode(1);
|
||||
ListNode *n1 = newListNode(3);
|
||||
ListNode *n2 = newListNode(2);
|
||||
ListNode *n3 = newListNode(5);
|
||||
ListNode *n4 = newListNode(4);
|
||||
// Set up references between the nodes
|
||||
// Link the nodes together
|
||||
n0->next = n1;
|
||||
n1->next = n2;
|
||||
n2->next = n3;
|
||||
@@ -67,21 +67,21 @@ int main() {
|
||||
|
||||
/* Insert a node */
|
||||
insert(n0, newListNode(0));
|
||||
printf("Linked list after inserting a node:\r\n");
|
||||
printf("Linked list after insertion:\r\n");
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Remove a node */
|
||||
removeItem(n0);
|
||||
printf("Linked list after removing a node:\r\n");
|
||||
printf("Linked list after removal:\r\n");
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Access a node */
|
||||
ListNode *node = access(n0, 3);
|
||||
printf("Value of the linked list node at index 3 = %d\r\n", node->val);
|
||||
printf("Value of the node at index 3 = %d\r\n", node->val);
|
||||
|
||||
/* Find a node */
|
||||
int index = find(n0, 2);
|
||||
printf("Index of the linked list node with value 2 = %d\r\n", index);
|
||||
printf("Index of the node with value 2 = %d\r\n", index);
|
||||
|
||||
// Free memory
|
||||
freeMemoryLinkedList(n0);
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* List structure */
|
||||
/* List class */
|
||||
typedef struct {
|
||||
int *arr; // Array (stores the list elements)
|
||||
int *arr; // Array that stores the list elements
|
||||
int capacity; // List capacity
|
||||
int size; // List size
|
||||
int extendRatio; // List capacity growth factor
|
||||
int extendRatio; // Factor by which the list capacity grows
|
||||
} MyList;
|
||||
|
||||
void extendCapacity(MyList *nums);
|
||||
@@ -32,7 +32,7 @@ void delMyList(MyList *nums) {
|
||||
free(nums);
|
||||
}
|
||||
|
||||
/* Get the list size */
|
||||
/* Get the list length */
|
||||
int size(MyList *nums) {
|
||||
return nums->size;
|
||||
}
|
||||
@@ -54,10 +54,10 @@ void set(MyList *nums, int index, int num) {
|
||||
nums->arr[index] = num;
|
||||
}
|
||||
|
||||
/* Append an element at the end */
|
||||
/* Append an element */
|
||||
void add(MyList *nums, int num) {
|
||||
if (size(nums) == capacity(nums)) {
|
||||
extendCapacity(nums); // Grow the capacity
|
||||
extendCapacity(nums); // Increase capacity
|
||||
}
|
||||
nums->arr[size(nums)] = num;
|
||||
nums->size++;
|
||||
@@ -66,9 +66,9 @@ void add(MyList *nums, int num) {
|
||||
/* Insert an element in the middle */
|
||||
void insert(MyList *nums, int index, int num) {
|
||||
assert(index >= 0 && index < size(nums));
|
||||
// Grow the capacity when adding an element would exceed it
|
||||
// Increase capacity when the elements would no longer fit
|
||||
if (size(nums) == capacity(nums)) {
|
||||
extendCapacity(nums); // Grow the capacity
|
||||
extendCapacity(nums); // Increase capacity
|
||||
}
|
||||
for (int i = size(nums); i > index; --i) {
|
||||
nums->arr[i] = nums->arr[i - 1];
|
||||
@@ -78,7 +78,7 @@ void insert(MyList *nums, int index, int num) {
|
||||
}
|
||||
|
||||
/* Remove an element */
|
||||
// Note: stdio.h already declares a function named remove
|
||||
// Note: stdio.h already uses the name remove
|
||||
int removeItem(MyList *nums, int index) {
|
||||
assert(index >= 0 && index < size(nums));
|
||||
int num = nums->arr[index];
|
||||
@@ -89,21 +89,21 @@ int removeItem(MyList *nums, int index) {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Grow the list capacity */
|
||||
/* Increase the list capacity */
|
||||
void extendCapacity(MyList *nums) {
|
||||
// Allocate new space first
|
||||
// Allocate space first
|
||||
int newCapacity = capacity(nums) * nums->extendRatio;
|
||||
int *extend = (int *)malloc(sizeof(int) * newCapacity);
|
||||
int *temp = nums->arr;
|
||||
|
||||
// Copy the old data into the new array
|
||||
// Copy the old data into the new space
|
||||
for (int i = 0; i < size(nums); i++)
|
||||
extend[i] = nums->arr[i];
|
||||
|
||||
// Free the old array
|
||||
// Free the old storage
|
||||
free(temp);
|
||||
|
||||
// Update the array pointer and capacity
|
||||
// Use the new storage
|
||||
nums->arr = extend;
|
||||
nums->capacity = newCapacity;
|
||||
}
|
||||
@@ -113,11 +113,11 @@ int *toArray(MyList *nums) {
|
||||
return nums->arr;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Initialize the list */
|
||||
MyList *nums = newMyList();
|
||||
/* Append an element at the end */
|
||||
/* Append an element */
|
||||
add(nums, 1);
|
||||
add(nums, 3);
|
||||
add(nums, 2);
|
||||
@@ -125,36 +125,36 @@ int main() {
|
||||
add(nums, 4);
|
||||
printf("List nums = ");
|
||||
printArray(toArray(nums), size(nums));
|
||||
printf("Capacity = %d, size = %d\n", capacity(nums), size(nums));
|
||||
printf("Capacity = %d, length = %d\n", capacity(nums), size(nums));
|
||||
|
||||
/* Insert an element in the middle */
|
||||
insert(nums, 3, 6);
|
||||
printf("Insert the number 6 at index 3, giving nums = ");
|
||||
printf("After inserting 6 at index 3, nums = ");
|
||||
printArray(toArray(nums), size(nums));
|
||||
|
||||
/* Remove an element */
|
||||
removeItem(nums, 3);
|
||||
printf("Remove the element at index 3, giving nums = ");
|
||||
printf("After removing the element at index 3, nums = ");
|
||||
printArray(toArray(nums), size(nums));
|
||||
|
||||
/* Access an element */
|
||||
int num = get(nums, 1);
|
||||
printf("Access the element at index 1; num = %d\n", num);
|
||||
printf("Reading index 1 gives num = %d\n", num);
|
||||
|
||||
/* Update an element */
|
||||
set(nums, 1, 0);
|
||||
printf("Update the element at index 1 to 0, giving nums = ");
|
||||
printf("After setting the element at index 1 to 0, nums = ");
|
||||
printArray(toArray(nums), size(nums));
|
||||
|
||||
/* Test capacity growth */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
// When i = 5, the list length would exceed its capacity, triggering capacity growth
|
||||
// At i = 5, the list length would exceed its capacity, so the list grows
|
||||
add(nums, i);
|
||||
}
|
||||
|
||||
printf("List after capacity growth, nums = ");
|
||||
printf("After increasing capacity, nums = ");
|
||||
printArray(toArray(nums), size(nums));
|
||||
printf("Capacity = %d, size = %d\n", capacity(nums), size(nums));
|
||||
printf("Capacity = %d, length = %d\n", capacity(nums), size(nums));
|
||||
|
||||
/* Free the allocated memory */
|
||||
delMyList(nums);
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/* Backtracking: n-queens */
|
||||
void backtrack(int row, int n, char state[MAX_SIZE][MAX_SIZE], char ***res, int *resSize, bool cols[MAX_SIZE],
|
||||
bool diags1[2 * MAX_SIZE - 1], bool diags2[2 * MAX_SIZE - 1]) {
|
||||
// Record a solution when a queen has been placed in every row
|
||||
// Record the solution once every row has a queen
|
||||
if (row == n) {
|
||||
res[*resSize] = (char **)malloc(sizeof(char *) * n);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
@@ -21,19 +21,19 @@ void backtrack(int row, int n, char state[MAX_SIZE][MAX_SIZE], char ***res, int
|
||||
(*resSize)++;
|
||||
return;
|
||||
}
|
||||
// Iterate over all columns
|
||||
// Try each column
|
||||
for (int col = 0; col < n; col++) {
|
||||
// Calculate the main-diagonal and anti-diagonal indices for this square
|
||||
// Find the two diagonals through this square
|
||||
int diag1 = row - col + n - 1;
|
||||
int diag2 = row + col;
|
||||
// Prune: the square must have no queen in its column, main diagonal, or anti-diagonal
|
||||
// Prune if the column or either diagonal already has a queen
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// Try: place a queen on this square
|
||||
// Try placing a queen on this square
|
||||
state[row][col] = 'Q';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// Place a queen in the next row
|
||||
backtrack(row + 1, n, state, res, resSize, cols, diags1, diags2);
|
||||
// Backtrack: restore this square to empty
|
||||
// Backtrack: clear this square
|
||||
state[row][col] = '#';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
@@ -43,16 +43,16 @@ void backtrack(int row, int n, char state[MAX_SIZE][MAX_SIZE], char ***res, int
|
||||
/* Solve the n-queens problem */
|
||||
char ***nQueens(int n, int *returnSize) {
|
||||
char state[MAX_SIZE][MAX_SIZE];
|
||||
// Initialize an n*n board, where 'Q' represents a queen and '#' represents an empty square
|
||||
// Set up an n-by-n board with 'Q' for a queen and '#' for an empty square
|
||||
for (int i = 0; i < n; ++i) {
|
||||
for (int j = 0; j < n; ++j) {
|
||||
state[i][j] = '#';
|
||||
}
|
||||
state[i][n] = '\0';
|
||||
}
|
||||
bool cols[MAX_SIZE] = {false}; // Track whether a column contains a queen
|
||||
bool diags1[2 * MAX_SIZE - 1] = {false}; // Track whether a main diagonal contains a queen
|
||||
bool diags2[2 * MAX_SIZE - 1] = {false}; // Track whether an anti-diagonal contains a queen
|
||||
bool cols[MAX_SIZE] = {false}; // Track occupied columns
|
||||
bool diags1[2 * MAX_SIZE - 1] = {false}; // Track occupied main diagonals
|
||||
bool diags2[2 * MAX_SIZE - 1] = {false}; // Track occupied secondary diagonals
|
||||
|
||||
char ***res = (char ***)malloc(sizeof(char **) * MAX_SIZE);
|
||||
*returnSize = 0;
|
||||
@@ -66,8 +66,8 @@ int main() {
|
||||
int returnSize;
|
||||
char ***res = nQueens(n, &returnSize);
|
||||
|
||||
printf("Board width and height: %d\n", n);
|
||||
printf("Number of queen placement solutions: %d\n", returnSize);
|
||||
printf("Board side length: %d\n", n);
|
||||
printf("Number of queen arrangements: %d\n", returnSize);
|
||||
for (int i = 0; i < returnSize; ++i) {
|
||||
for (int j = 0; j < n; ++j) {
|
||||
printf("[");
|
||||
@@ -82,7 +82,7 @@ int main() {
|
||||
printf("---------------------\n");
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i < returnSize; ++i) {
|
||||
for (int j = 0; j < n; ++j) {
|
||||
free(res[i][j]);
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume there are at most 1000 permutations
|
||||
// Assume at most 1000 permutations
|
||||
#define MAX_SIZE 1000
|
||||
|
||||
/* Backtracking: permutations I */
|
||||
void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *selected, int **res, int *resSize) {
|
||||
// Record a solution when the state length equals the number of elements
|
||||
// Record a solution when the state contains all the elements
|
||||
if (stateSize == choicesSize) {
|
||||
res[*resSize] = (int *)malloc(choicesSize * sizeof(int));
|
||||
for (int i = 0; i < choicesSize; i++) {
|
||||
@@ -20,17 +20,17 @@ void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *s
|
||||
(*resSize)++;
|
||||
return;
|
||||
}
|
||||
// Iterate over all choices
|
||||
// Try each choice
|
||||
for (int i = 0; i < choicesSize; i++) {
|
||||
int choice = choices[i];
|
||||
// Prune: do not choose an element more than once
|
||||
// Prune: skip elements already in use
|
||||
if (!selected[i]) {
|
||||
// Try: make a choice and update the state
|
||||
// Make a choice and update the state
|
||||
selected[i] = true;
|
||||
state[stateSize] = choice;
|
||||
// Proceed to the next choice
|
||||
// Make the next choice
|
||||
backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
// Backtrack: undo the choice to restore the previous state
|
||||
selected[i] = false;
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ int main() {
|
||||
printArray(res[i], numsSize);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i < returnSize; i++) {
|
||||
free(res[i]);
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume at most 1000 permutations and a maximum element value of 1000
|
||||
// Assume at most 1000 permutations and element values at most 1000
|
||||
#define MAX_SIZE 1000
|
||||
|
||||
/* Backtracking: permutations II */
|
||||
void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *selected, int **res, int *resSize) {
|
||||
// Record a solution when the state length equals the number of elements
|
||||
// Record a solution when the state contains all the elements
|
||||
if (stateSize == choicesSize) {
|
||||
res[*resSize] = (int *)malloc(choicesSize * sizeof(int));
|
||||
for (int i = 0; i < choicesSize; i++) {
|
||||
@@ -20,19 +20,19 @@ void backtrack(int *state, int stateSize, int *choices, int choicesSize, bool *s
|
||||
(*resSize)++;
|
||||
return;
|
||||
}
|
||||
// Iterate over all choices
|
||||
// Try each choice
|
||||
bool duplicated[MAX_SIZE] = {false};
|
||||
for (int i = 0; i < choicesSize; i++) {
|
||||
int choice = choices[i];
|
||||
// Prune: do not reuse an element or choose the same value again at this depth
|
||||
// Skip elements already in use and values already tried at this level
|
||||
if (!selected[i] && !duplicated[choice]) {
|
||||
// Try: make a choice and update the state
|
||||
duplicated[choice] = true; // Record the chosen value
|
||||
// Make a choice and update the state
|
||||
duplicated[choice] = true; // Track values already tried
|
||||
selected[i] = true;
|
||||
state[stateSize] = choice;
|
||||
// Proceed to the next choice
|
||||
// Make the next choice
|
||||
backtrack(state, stateSize + 1, choices, choicesSize, selected, res, resSize);
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
// Backtrack: undo the choice to restore the previous state
|
||||
selected[i] = false;
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ int main() {
|
||||
printArray(res[i], numsSize);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i < returnSize; i++) {
|
||||
free(res[i]);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume the result contains at most 100 entries
|
||||
// Assume the result has length at most 100
|
||||
#define MAX_SIZE 100
|
||||
|
||||
TreeNode *res[MAX_SIZE];
|
||||
@@ -42,7 +42,7 @@ int main() {
|
||||
}
|
||||
printArray(vals, resSize);
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
freeMemoryTree(root);
|
||||
free(vals);
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume each path and the result list contain at most 100 entries
|
||||
// Assume the path and the result each have length at most 100
|
||||
#define MAX_SIZE 100
|
||||
#define MAX_RES_SIZE 100
|
||||
|
||||
@@ -19,7 +19,7 @@ void preOrder(TreeNode *root) {
|
||||
if (root == NULL) {
|
||||
return;
|
||||
}
|
||||
// Try
|
||||
// Try a choice
|
||||
path[pathSize++] = root;
|
||||
if (root->val == 7) {
|
||||
// Record the solution
|
||||
@@ -44,7 +44,7 @@ int main() {
|
||||
// Preorder traversal
|
||||
preOrder(root);
|
||||
|
||||
printf("\nPrint all paths from the root to nodes with value 7\n");
|
||||
printf("\nPrint all paths from the root to a node with value 7\n");
|
||||
for (int i = 0; i < resSize; ++i) {
|
||||
int *vals = malloc(MAX_SIZE * sizeof(int));
|
||||
int size = 0;
|
||||
@@ -55,7 +55,7 @@ int main() {
|
||||
free(vals);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
freeMemoryTree(root);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume each path and the result list contain at most 100 entries
|
||||
// Assume the path and the result each have length at most 100
|
||||
#define MAX_SIZE 100
|
||||
#define MAX_RES_SIZE 100
|
||||
|
||||
@@ -20,7 +20,7 @@ void preOrder(TreeNode *root) {
|
||||
if (root == NULL || root->val == 3) {
|
||||
return;
|
||||
}
|
||||
// Try
|
||||
// Try a choice
|
||||
path[pathSize++] = root;
|
||||
if (root->val == 7) {
|
||||
// Record the solution
|
||||
@@ -45,7 +45,7 @@ int main() {
|
||||
// Preorder traversal
|
||||
preOrder(root);
|
||||
|
||||
printf("\nPrint all paths from the root to nodes with value 7 that contain no node with value 3\n");
|
||||
printf("\nPrint all paths from the root to a node with value 7 that avoid nodes with value 3\n");
|
||||
for (int i = 0; i < resSize; ++i) {
|
||||
int *vals = malloc(MAX_SIZE * sizeof(int));
|
||||
int size = 0;
|
||||
@@ -56,7 +56,7 @@ int main() {
|
||||
free(vals);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
freeMemoryTree(root);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume each path and the result list contain at most 100 entries
|
||||
// Assume the path and the result each have length at most 100
|
||||
#define MAX_SIZE 100
|
||||
#define MAX_RES_SIZE 100
|
||||
|
||||
@@ -27,7 +27,7 @@ void recordSolution(void) {
|
||||
resSize++;
|
||||
}
|
||||
|
||||
/* Check whether the choice is valid in the current state */
|
||||
/* Check whether this choice is valid in the current state */
|
||||
bool isValid(TreeNode *choice) {
|
||||
return choice != NULL && choice->val != 3;
|
||||
}
|
||||
@@ -44,22 +44,22 @@ void undoChoice(void) {
|
||||
|
||||
/* Backtracking: example 3 */
|
||||
void backtrack(TreeNode *choices[2]) {
|
||||
// Check whether this is a solution
|
||||
// Check for a solution
|
||||
if (isSolution()) {
|
||||
// Record the solution
|
||||
recordSolution();
|
||||
}
|
||||
// Iterate over all choices
|
||||
// Try each choice
|
||||
for (int i = 0; i < 2; i++) {
|
||||
TreeNode *choice = choices[i];
|
||||
// Prune: check whether the choice is valid
|
||||
if (isValid(choice)) {
|
||||
// Try: make a choice and update the state
|
||||
// Make a choice and update the state
|
||||
makeChoice(choice);
|
||||
// Proceed to the next choice
|
||||
// Make the next choice
|
||||
TreeNode *nextChoices[2] = {choice->left, choice->right};
|
||||
backtrack(nextChoices);
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
// Backtrack: undo the choice to restore the previous state
|
||||
undoChoice();
|
||||
}
|
||||
}
|
||||
@@ -72,11 +72,11 @@ int main() {
|
||||
printf("\nInitialize the binary tree\n");
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
// Backtracking
|
||||
TreeNode *choices[2] = {root, NULL};
|
||||
backtrack(choices);
|
||||
|
||||
printf("\nPrint all paths from the root to nodes with value 7 that contain no node with value 3\n");
|
||||
printf("\nPrint all paths from the root to a node with value 7 that avoid nodes with value 3\n");
|
||||
for (int i = 0; i < resSize; ++i) {
|
||||
int *vals = malloc(MAX_SIZE * sizeof(int));
|
||||
int size = 0;
|
||||
@@ -87,7 +87,7 @@ int main() {
|
||||
free(vals);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
freeMemoryTree(root);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -9,18 +9,18 @@
|
||||
#define MAX_SIZE 100
|
||||
#define MAX_RES_SIZE 100
|
||||
|
||||
// State (subset)
|
||||
// State (current subset)
|
||||
int state[MAX_SIZE];
|
||||
int stateSize = 0;
|
||||
|
||||
// Result list (list of subsets)
|
||||
// Results (list of subsets)
|
||||
int res[MAX_RES_SIZE][MAX_SIZE];
|
||||
int resColSizes[MAX_RES_SIZE];
|
||||
int resSize = 0;
|
||||
|
||||
/* Backtracking: subset sum I */
|
||||
void backtrack(int target, int *choices, int choicesSize, int start) {
|
||||
// Record a solution when the remaining target is 0
|
||||
// Record a solution when the subset sums to target
|
||||
if (target == 0) {
|
||||
for (int i = 0; i < stateSize; ++i) {
|
||||
res[resSize][i] = state[i];
|
||||
@@ -28,20 +28,20 @@ void backtrack(int target, int *choices, int choicesSize, int start) {
|
||||
resColSizes[resSize++] = stateSize;
|
||||
return;
|
||||
}
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
// Try each choice
|
||||
// Pruning rule 2: start at start to avoid duplicate subsets
|
||||
for (int i = start; i < choicesSize; i++) {
|
||||
// Pruning 1: exit the loop if the choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and also exceed the remaining target
|
||||
// Pruning rule 1: break if the subset sum would exceed target
|
||||
// The array is sorted, so later elements are at least as large and would also take the sum over target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Try: make a choice and update target and start
|
||||
// Make a choice and update target and start
|
||||
state[stateSize] = choices[i];
|
||||
stateSize++;
|
||||
// Proceed to the next choice
|
||||
// Make the next choice
|
||||
backtrack(target - choices[i], choices, choicesSize, i);
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
// Backtrack: undo the choice to restore the previous state
|
||||
stateSize--;
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ int cmp(const void *a, const void *b) {
|
||||
/* Solve subset sum I */
|
||||
void subsetSumI(int *nums, int numsSize, int target) {
|
||||
qsort(nums, numsSize, sizeof(int), cmp); // Sort nums
|
||||
int start = 0; // Starting index for iteration
|
||||
int start = 0; // Starting index
|
||||
backtrack(target, nums, numsSize, start);
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ int main() {
|
||||
printf("Input array nums = ");
|
||||
printArray(nums, numsSize);
|
||||
printf("target = %d\n", target);
|
||||
printf("All subsets whose sum equals %d, res = \n", target);
|
||||
printf("Subsets that sum to %d: res = \n", target);
|
||||
for (int i = 0; i < resSize; ++i) {
|
||||
printArray(res[i], resColSizes[i]);
|
||||
}
|
||||
|
||||
@@ -9,18 +9,18 @@
|
||||
#define MAX_SIZE 100
|
||||
#define MAX_RES_SIZE 100
|
||||
|
||||
// State (subset)
|
||||
// State (current subset)
|
||||
int state[MAX_SIZE];
|
||||
int stateSize = 0;
|
||||
|
||||
// Result list (list of subsets)
|
||||
// Results (list of subsets)
|
||||
int res[MAX_RES_SIZE][MAX_SIZE];
|
||||
int resColSizes[MAX_RES_SIZE];
|
||||
int resSize = 0;
|
||||
|
||||
/* Backtracking: subset sum I */
|
||||
void backtrack(int target, int total, int *choices, int choicesSize) {
|
||||
// Record a solution when the subset sum equals target
|
||||
// Record a solution when the subset sums to target
|
||||
if (total == target) {
|
||||
for (int i = 0; i < stateSize; i++) {
|
||||
res[resSize][i] = state[i];
|
||||
@@ -28,22 +28,22 @@ void backtrack(int target, int total, int *choices, int choicesSize) {
|
||||
resColSizes[resSize++] = stateSize;
|
||||
return;
|
||||
}
|
||||
// Iterate over all choices
|
||||
// Try each choice
|
||||
for (int i = 0; i < choicesSize; i++) {
|
||||
// Prune: skip this choice if the subset sum would exceed target
|
||||
// Prune: skip choices that would take the subset sum over target
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// Try: make a choice and update the sum total
|
||||
// Make a choice and update the running sum total
|
||||
state[stateSize++] = choices[i];
|
||||
// Proceed to the next choice
|
||||
// Make the next choice
|
||||
backtrack(target, total + choices[i], choices, choicesSize);
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
// Backtrack: undo the choice to restore the previous state
|
||||
stateSize--;
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (with duplicate subsets) */
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
void subsetSumINaive(int *nums, int numsSize, int target) {
|
||||
resSize = 0; // Initialize the solution count to 0
|
||||
backtrack(target, 0, nums, numsSize);
|
||||
@@ -60,7 +60,7 @@ int main() {
|
||||
printf("Input array nums = ");
|
||||
printArray(nums, numsSize);
|
||||
printf("target = %d\n", target);
|
||||
printf("All subsets whose sum equals %d, res = \n", target);
|
||||
printf("Subsets that sum to %d: res = \n", target);
|
||||
for (int i = 0; i < resSize; i++) {
|
||||
printArray(res[i], resColSizes[i]);
|
||||
}
|
||||
|
||||
@@ -9,18 +9,18 @@
|
||||
#define MAX_SIZE 100
|
||||
#define MAX_RES_SIZE 100
|
||||
|
||||
// State (subset)
|
||||
// State (current subset)
|
||||
int state[MAX_SIZE];
|
||||
int stateSize = 0;
|
||||
|
||||
// Result list (list of subsets)
|
||||
// Results (list of subsets)
|
||||
int res[MAX_RES_SIZE][MAX_SIZE];
|
||||
int resColSizes[MAX_RES_SIZE];
|
||||
int resSize = 0;
|
||||
|
||||
/* Backtracking: subset sum II */
|
||||
void backtrack(int target, int *choices, int choicesSize, int start) {
|
||||
// Record a solution when the remaining target is 0
|
||||
// Record a solution when the subset sums to target
|
||||
if (target == 0) {
|
||||
for (int i = 0; i < stateSize; i++) {
|
||||
res[resSize][i] = state[i];
|
||||
@@ -28,24 +28,24 @@ void backtrack(int target, int *choices, int choicesSize, int start) {
|
||||
resColSizes[resSize++] = stateSize;
|
||||
return;
|
||||
}
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
// Pruning 3: iterate from start to avoid choosing the same element again
|
||||
// Try each choice
|
||||
// Pruning rule 2: start at start to avoid duplicate subsets
|
||||
// Pruning rule 3: start at start to avoid reusing the same element
|
||||
for (int i = start; i < choicesSize; i++) {
|
||||
// Pruning 1: skip this choice if it exceeds the remaining target
|
||||
// Pruning rule 1: skip choices that would take the sum over target
|
||||
if (target - choices[i] < 0) {
|
||||
continue;
|
||||
}
|
||||
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
|
||||
// Pruning rule 4: skip a value equal to its left neighbor, since its search branch is a duplicate
|
||||
if (i > start && choices[i] == choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// Try: make a choice and update target and start
|
||||
// Make a choice and update target and start
|
||||
state[stateSize] = choices[i];
|
||||
stateSize++;
|
||||
// Proceed to the next choice
|
||||
// Make the next choice
|
||||
backtrack(target - choices[i], choices, choicesSize, i + 1);
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
// Backtrack: undo the choice to restore the previous state
|
||||
stateSize--;
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ int main() {
|
||||
printf("Input array nums = ");
|
||||
printArray(nums, numsSize);
|
||||
printf("target = %d\n", target);
|
||||
printf("All subsets whose sum equals %d, res = \n", target);
|
||||
printf("Subsets that sum to %d: res = \n", target);
|
||||
for (int i = 0; i < resSize; ++i) {
|
||||
printArray(res[i], resColSizes[i]);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
/* Sum using iteration */
|
||||
/* Iterative sum */
|
||||
int sumIter(int n) {
|
||||
int res = 0;
|
||||
for (int i = 1; i <= n; i++) {
|
||||
@@ -15,7 +15,7 @@ int sumIter(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Sum using recursion */
|
||||
/* Recursive sum */
|
||||
int sumRecur(int n) {
|
||||
if (n == 1) {
|
||||
return 1;
|
||||
|
||||
@@ -44,7 +44,7 @@ int whileLoopII(int n) {
|
||||
|
||||
/* Nested for loops */
|
||||
char *nestedForLoop(int n) {
|
||||
// There are n * n points; each "(i, j), " takes at most 6+10*2 characters, plus space for the final null character \0
|
||||
// There are n * n points. Each "(i, j), " takes at most 6+10*2 characters. Allow one extra byte for the final null character \0.
|
||||
int size = n * n * 26 + 1;
|
||||
char *res = malloc(size * sizeof(char));
|
||||
// Loop over i = 1, 2, ..., n-1, n
|
||||
@@ -59,22 +59,22 @@ char *nestedForLoop(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = forLoop(n);
|
||||
printf("\nSum from the for loop, res = %d\n", res);
|
||||
printf("\nfor loop sum: res = %d\n", res);
|
||||
|
||||
res = whileLoop(n);
|
||||
printf("\nSum from the while loop, res = %d\n", res);
|
||||
printf("\nwhile loop sum: res = %d\n", res);
|
||||
|
||||
res = whileLoopII(n);
|
||||
printf("\nSum from the while loop (two updates), res = %d\n", res);
|
||||
printf("\nwhile loop sum (two updates): res = %d\n", res);
|
||||
|
||||
char *resStr = nestedForLoop(n);
|
||||
printf("\nTraversal result from nested for loops: %s\r\n", resStr);
|
||||
printf("\nNested for loop traversal: %s\r\n", resStr);
|
||||
free(resStr);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -11,25 +11,25 @@ int recur(int n) {
|
||||
// Base case
|
||||
if (n == 1)
|
||||
return 1;
|
||||
// Recurse: make a recursive call
|
||||
// Descend: make a recursive call
|
||||
int res = recur(n - 1);
|
||||
// Unwind: return the result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
/* Simulate recursion using iteration */
|
||||
/* Simulate recursion with iteration */
|
||||
int forLoopRecur(int n) {
|
||||
int stack[1000]; // Use a large array to simulate a stack
|
||||
int top = -1; // Top-of-stack index
|
||||
int stack[1000]; // Use a large array as a stack
|
||||
int top = -1; // Index of the top of the stack
|
||||
int res = 0;
|
||||
// Recurse: make a recursive call
|
||||
// Descend: make a recursive call
|
||||
for (int i = n; i > 0; i--) {
|
||||
// Simulate recursive calls by pushing onto the stack
|
||||
// Push to simulate descending
|
||||
stack[1 + top++] = i;
|
||||
}
|
||||
// Unwind: return the result
|
||||
while (top >= 0) {
|
||||
// Simulate unwinding by popping from the stack
|
||||
// Pop to simulate unwinding
|
||||
res += stack[top--];
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
@@ -41,11 +41,11 @@ int tailRecur(int n, int res) {
|
||||
// Base case
|
||||
if (n == 0)
|
||||
return res;
|
||||
// Tail-recursive call
|
||||
// Tail call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
/* Fibonacci sequence using recursion */
|
||||
int fib(int n) {
|
||||
// Base cases: f(1) = 0, f(2) = 1
|
||||
if (n == 1 || n == 2)
|
||||
@@ -56,19 +56,19 @@ int fib(int n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 5;
|
||||
int res;
|
||||
|
||||
res = recur(n);
|
||||
printf("\nSum from the recursive function, res = %d\n", res);
|
||||
printf("\nRecursive sum: res = %d\n", res);
|
||||
|
||||
res = forLoopRecur(n);
|
||||
printf("\nSum from simulating recursion with iteration, res = %d\n", res);
|
||||
printf("\nSum using simulated recursion: res = %d\n", res);
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
printf("\nSum from the tail-recursive function, res = %d\n", res);
|
||||
printf("\nTail-recursive sum: res = %d\n", res);
|
||||
|
||||
res = fib(n);
|
||||
printf("\nFibonacci term %d is %d\n", n, res);
|
||||
|
||||
@@ -12,19 +12,19 @@ int func() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Constant complexity */
|
||||
/* Constant space */
|
||||
void constant(int n) {
|
||||
// Constants, variables, and objects occupy O(1) space
|
||||
// Constants, variables, and objects use O(1) space
|
||||
const int a = 0;
|
||||
int b = 0;
|
||||
int nums[1000];
|
||||
ListNode *node = newListNode(0);
|
||||
free(node);
|
||||
// Variables in the loop occupy O(1) space
|
||||
// Variables in the loop use O(1) space
|
||||
for (int i = 0; i < n; i++) {
|
||||
int c = 0;
|
||||
}
|
||||
// Function calls in the loop occupy O(1) space
|
||||
// Function calls in the loop use O(1) space
|
||||
for (int i = 0; i < n; i++) {
|
||||
func();
|
||||
}
|
||||
@@ -34,27 +34,27 @@ void constant(int n) {
|
||||
typedef struct {
|
||||
int key;
|
||||
int val;
|
||||
UT_hash_handle hh; // Implemented using uthash.h
|
||||
UT_hash_handle hh; // Implemented with uthash.h
|
||||
} HashTable;
|
||||
|
||||
/* Linear complexity */
|
||||
/* Linear space */
|
||||
void linear(int n) {
|
||||
// An array of length n uses O(n) space
|
||||
int *nums = malloc(sizeof(int) * n);
|
||||
free(nums);
|
||||
|
||||
// A list of length n occupies O(n) space
|
||||
// A list of length n uses O(n) space
|
||||
ListNode **nodes = malloc(sizeof(ListNode *) * n);
|
||||
for (int i = 0; i < n; i++) {
|
||||
nodes[i] = newListNode(i);
|
||||
}
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i < n; i++) {
|
||||
free(nodes[i]);
|
||||
}
|
||||
free(nodes);
|
||||
|
||||
// A hash table with n entries occupies O(n) space
|
||||
// A hash table with n entries uses O(n) space
|
||||
HashTable *h = NULL;
|
||||
for (int i = 0; i < n; i++) {
|
||||
HashTable *tmp = malloc(sizeof(HashTable));
|
||||
@@ -63,7 +63,7 @@ void linear(int n) {
|
||||
HASH_ADD_INT(h, key, tmp);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
HashTable *curr, *tmp;
|
||||
HASH_ITER(hh, h, curr, tmp) {
|
||||
HASH_DEL(h, curr);
|
||||
@@ -71,17 +71,17 @@ void linear(int n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear complexity (recursive implementation) */
|
||||
/* Linear space (recursive) */
|
||||
void linearRecur(int n) {
|
||||
printf("Recursive call n = %d\r\n", n);
|
||||
printf("Recursive call: n = %d\r\n", n);
|
||||
if (n == 1)
|
||||
return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Quadratic complexity */
|
||||
/* Quadratic space */
|
||||
void quadratic(int n) {
|
||||
// The two-dimensional list occupies O(n^2) space
|
||||
// A two-dimensional list uses O(n^2) space
|
||||
int **numMatrix = malloc(sizeof(int *) * n);
|
||||
for (int i = 0; i < n; i++) {
|
||||
int *tmp = malloc(sizeof(int) * n);
|
||||
@@ -91,25 +91,25 @@ void quadratic(int n) {
|
||||
numMatrix[i] = tmp;
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i < n; i++) {
|
||||
free(numMatrix[i]);
|
||||
}
|
||||
free(numMatrix);
|
||||
}
|
||||
|
||||
/* Quadratic complexity (recursive implementation) */
|
||||
/* Quadratic space (recursive) */
|
||||
int quadraticRecur(int n) {
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
int *nums = malloc(sizeof(int) * n);
|
||||
printf("In recursive call n = %d, nums has length = %d\r\n", n, n);
|
||||
printf("Recursive call: n = %d, length of nums = %d\r\n", n, n);
|
||||
int res = quadraticRecur(n - 1);
|
||||
free(nums);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Exponential complexity (building a perfect binary tree) */
|
||||
/* Exponential space (build a perfect binary tree) */
|
||||
TreeNode *buildTree(int n) {
|
||||
if (n == 0)
|
||||
return NULL;
|
||||
@@ -119,22 +119,22 @@ TreeNode *buildTree(int n) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 5;
|
||||
// Constant complexity
|
||||
// Constant space
|
||||
constant(n);
|
||||
// Linear complexity
|
||||
// Linear space
|
||||
linear(n);
|
||||
linearRecur(n);
|
||||
// Quadratic complexity
|
||||
// Quadratic space
|
||||
quadratic(n);
|
||||
quadraticRecur(n);
|
||||
// Exponential complexity
|
||||
// Exponential space
|
||||
TreeNode *root = buildTree(n);
|
||||
printTree(root);
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
freeMemoryTree(root);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Constant complexity */
|
||||
/* Constant time */
|
||||
int constant(int n) {
|
||||
int count = 0;
|
||||
int size = 100000;
|
||||
@@ -16,7 +16,7 @@ int constant(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear complexity */
|
||||
/* Linear time */
|
||||
int linear(int n) {
|
||||
int count = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
@@ -25,20 +25,20 @@ int linear(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear complexity (array traversal) */
|
||||
/* Linear time (array traversal) */
|
||||
int arrayTraversal(int *nums, int n) {
|
||||
int count = 0;
|
||||
// The number of iterations is proportional to the array length
|
||||
// The iteration count is proportional to the array length
|
||||
for (int i = 0; i < n; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Quadratic complexity */
|
||||
/* Quadratic time */
|
||||
int quadratic(int n) {
|
||||
int count = 0;
|
||||
// The number of iterations is proportional to the square of the input size n
|
||||
// The iteration count grows quadratically with input size n
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
count++;
|
||||
@@ -47,12 +47,12 @@ int quadratic(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Quadratic complexity (bubble sort) */
|
||||
/* Quadratic time (bubble sort) */
|
||||
int bubbleSort(int *nums, int n) {
|
||||
int count = 0; // Counter
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is the closed interval [0, i]
|
||||
for (int i = n - 1; i > 0; i--) {
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
// Inner loop: swap adjacent elements to move the largest in [0, i] to index i
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
@@ -66,11 +66,11 @@ int bubbleSort(int *nums, int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential complexity (iterative implementation) */
|
||||
/* Exponential time (iterative) */
|
||||
int exponential(int n) {
|
||||
int count = 0;
|
||||
int bas = 1;
|
||||
// Each cell divides into two per round, giving the sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
// Each cell divides in two per round, giving 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < bas; j++) {
|
||||
count++;
|
||||
@@ -81,14 +81,14 @@ int exponential(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential complexity (recursive implementation) */
|
||||
/* Exponential time (recursive) */
|
||||
int expRecur(int n) {
|
||||
if (n == 1)
|
||||
return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* Logarithmic complexity (iterative implementation) */
|
||||
/* Logarithmic time (iterative) */
|
||||
int logarithmic(int n) {
|
||||
int count = 0;
|
||||
while (n > 1) {
|
||||
@@ -98,14 +98,14 @@ int logarithmic(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Logarithmic complexity (recursive implementation) */
|
||||
/* Logarithmic time (recursive) */
|
||||
int logRecur(int n) {
|
||||
if (n <= 1)
|
||||
return 0;
|
||||
return logRecur(n / 2) + 1;
|
||||
}
|
||||
|
||||
/* Linearithmic complexity */
|
||||
/* Linearithmic time */
|
||||
int linearLogRecur(int n) {
|
||||
if (n <= 1)
|
||||
return 1;
|
||||
@@ -116,7 +116,7 @@ int linearLogRecur(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Factorial complexity (recursive implementation) */
|
||||
/* Factorial time (recursive) */
|
||||
int factorialRecur(int n) {
|
||||
if (n == 0)
|
||||
return 1;
|
||||
@@ -127,45 +127,45 @@ int factorialRecur(int n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main(int argc, char *argv[]) {
|
||||
// Try different values of n to see how the operation count grows for each complexity
|
||||
int n = 8;
|
||||
printf("Input size n = %d\n", n);
|
||||
|
||||
int count = constant(n);
|
||||
printf("Operation count for constant complexity = %d\n", count);
|
||||
printf("Constant operation count = %d\n", count);
|
||||
|
||||
count = linear(n);
|
||||
printf("Operation count for linear complexity = %d\n", count);
|
||||
// Allocate heap memory for a one-dimensional array of n int elements
|
||||
printf("Linear operation count = %d\n", count);
|
||||
// Allocate heap memory for a one-dimensional array of n elements of type int
|
||||
int *nums = (int *)malloc(n * sizeof(int));
|
||||
count = arrayTraversal(nums, n);
|
||||
printf("Operation count for linear complexity (array traversal) = %d\n", count);
|
||||
printf("Linear operation count (array traversal) = %d\n", count);
|
||||
|
||||
count = quadratic(n);
|
||||
printf("Operation count for quadratic complexity = %d\n", count);
|
||||
printf("Quadratic operation count = %d\n", count);
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = n - i; // [n,n-1,...,2,1]
|
||||
}
|
||||
count = bubbleSort(nums, n);
|
||||
printf("Operation count for quadratic complexity (bubble sort) = %d\n", count);
|
||||
printf("Quadratic operation count (bubble sort) = %d\n", count);
|
||||
|
||||
count = exponential(n);
|
||||
printf("Operation count for exponential complexity (iteration) = %d\n", count);
|
||||
printf("Exponential operation count (iterative) = %d\n", count);
|
||||
count = expRecur(n);
|
||||
printf("Operation count for exponential complexity (recursion) = %d\n", count);
|
||||
printf("Exponential operation count (recursive) = %d\n", count);
|
||||
|
||||
count = logarithmic(n);
|
||||
printf("Operation count for logarithmic complexity (iteration) = %d\n", count);
|
||||
printf("Logarithmic operation count (iterative) = %d\n", count);
|
||||
count = logRecur(n);
|
||||
printf("Operation count for logarithmic complexity (recursion) = %d\n", count);
|
||||
printf("Logarithmic operation count (recursive) = %d\n", count);
|
||||
|
||||
count = linearLogRecur(n);
|
||||
printf("Operation count for linearithmic complexity (recursion) = %d\n", count);
|
||||
printf("Linearithmic operation count (recursive) = %d\n", count);
|
||||
|
||||
count = factorialRecur(n);
|
||||
printf("Operation count for factorial complexity (recursion) = %d\n", count);
|
||||
printf("Factorial operation count (recursive) = %d\n", count);
|
||||
|
||||
// Free the heap memory
|
||||
if (nums != NULL) {
|
||||
|
||||
@@ -6,15 +6,15 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Generate an array containing { 1, 2, ..., n } in shuffled order */
|
||||
/* Generate a shuffled array containing { 1, 2, ..., n } */
|
||||
int *randomNumbers(int n) {
|
||||
// Allocate heap memory for a one-dimensional array of n int elements
|
||||
// Allocate heap memory for a one-dimensional array of n elements of type int
|
||||
int *nums = (int *)malloc(n * sizeof(int));
|
||||
// Generate the array nums = { 1, 2, 3, ..., n }
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
// Randomly shuffle the array elements
|
||||
// Shuffle the array elements at random
|
||||
for (int i = n - 1; i > 0; i--) {
|
||||
int j = rand() % (i + 1);
|
||||
int temp = nums[i];
|
||||
@@ -24,18 +24,18 @@ int *randomNumbers(int n) {
|
||||
return nums;
|
||||
}
|
||||
|
||||
/* Find the index of the number 1 in array nums */
|
||||
/* Find the index of 1 in the array nums */
|
||||
int findOne(int *nums, int n) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
// When 1 is at the start of the array, the best-case time complexity is O(1)
|
||||
// When 1 is at the end of the array, the worst-case time complexity is O(n)
|
||||
// Best case: 1 is the first element, so the search takes O(1) time
|
||||
// Worst case: 1 is the last element, so the search takes O(n) time
|
||||
if (nums[i] == 1)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main(int argc, char *argv[]) {
|
||||
// Initialize the random seed
|
||||
srand((unsigned int)time(NULL));
|
||||
@@ -43,9 +43,9 @@ int main(int argc, char *argv[]) {
|
||||
int n = 100;
|
||||
int *nums = randomNumbers(n);
|
||||
int index = findOne(nums, n);
|
||||
printf("\nArray [ 1, 2, ..., n ] after shuffling = ");
|
||||
printf("\nShuffled array [ 1, 2, ..., n ] = ");
|
||||
printArray(nums, n);
|
||||
printf("Index of the number 1: %d\n", index);
|
||||
printf("Index of 1 = %d\n", index);
|
||||
// Free the heap memory
|
||||
if (nums != NULL) {
|
||||
free(nums);
|
||||
|
||||
@@ -8,20 +8,20 @@
|
||||
|
||||
/* Binary search: problem f(i, j) */
|
||||
int dfs(int nums[], int target, int i, int j) {
|
||||
// If the interval is empty, the target is absent; return -1
|
||||
// An empty interval contains no target, so return -1
|
||||
if (i > j) {
|
||||
return -1;
|
||||
}
|
||||
// Calculate the midpoint index m
|
||||
// Compute the middle index m
|
||||
int m = (i + j) / 2;
|
||||
if (nums[m] < target) {
|
||||
// Recurse on subproblem f(m+1, j)
|
||||
// Recursively solve f(m+1, j)
|
||||
return dfs(nums, target, m + 1, j);
|
||||
} else if (nums[m] > target) {
|
||||
// Recurse on subproblem f(i, m-1)
|
||||
// Recursively solve f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1);
|
||||
} else {
|
||||
// The target element was found; return its index
|
||||
// Target found: return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ int dfs(int nums[], int target, int i, int j) {
|
||||
/* Binary search */
|
||||
int binarySearch(int nums[], int target, int numsSize) {
|
||||
int n = numsSize;
|
||||
// Solve problem f(0, n-1)
|
||||
// Solve f(0, n-1)
|
||||
return dfs(nums, target, 0, n - 1);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ int main() {
|
||||
|
||||
// Binary search (closed interval)
|
||||
int index = binarySearch(nums, target, numsSize);
|
||||
printf("Index of target element 6 = %d\n", index);
|
||||
printf("Index of target 6 = %d\n", index);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
// Assume all elements are less than 1000
|
||||
#define MAX_SIZE 1000
|
||||
|
||||
/* Build a binary tree: divide and conquer */
|
||||
/* Build a binary tree using divide and conquer */
|
||||
TreeNode *dfs(int *preorder, int *inorderMap, int i, int l, int r, int size) {
|
||||
// Stop when the subtree interval is empty
|
||||
if (r - l < 0)
|
||||
return NULL;
|
||||
// Initialize the root node
|
||||
// Initialize the root
|
||||
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
|
||||
root->val = preorder[i];
|
||||
root->left = NULL;
|
||||
@@ -25,13 +25,13 @@ TreeNode *dfs(int *preorder, int *inorderMap, int i, int l, int r, int size) {
|
||||
root->left = dfs(preorder, inorderMap, i + 1, l, m - 1, size);
|
||||
// Subproblem: build the right subtree
|
||||
root->right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r, size);
|
||||
// Return the root node
|
||||
// Return the root
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Build a binary tree */
|
||||
TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) {
|
||||
// Initialize a lookup array mapping inorder values to their indices
|
||||
// Map each inorder value to its index in a hash table
|
||||
int *inorderMap = (int *)malloc(sizeof(int) * MAX_SIZE);
|
||||
for (int i = 0; i < inorderSize; i++) {
|
||||
inorderMap[inorder[i]] = i;
|
||||
@@ -53,7 +53,7 @@ int main() {
|
||||
printArray(inorder, inorderSize);
|
||||
|
||||
TreeNode *root = buildTree(preorder, preorderSize, inorder, inorderSize);
|
||||
printf("Constructed binary tree:\n");
|
||||
printf("Reconstructed binary tree:\n");
|
||||
printTree(root);
|
||||
|
||||
freeMemoryTree(root);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
/* Fast exponentiation */
|
||||
/* Exponentiation by squaring */
|
||||
int fastPow(int x, int n) {
|
||||
if (n == 0) {
|
||||
return 1;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume at most 1000 disks
|
||||
// Assume at most 1000 permutations
|
||||
#define MAX_SIZE 1000
|
||||
|
||||
/* Move one disk */
|
||||
@@ -20,22 +20,22 @@ void move(int *src, int *srcSize, int *tar, int *tarSize) {
|
||||
(*tarSize)++;
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
/* Solve Tower of Hanoi subproblem f(i) */
|
||||
void dfs(int i, int *src, int *srcSize, int *buf, int *bufSize, int *tar, int *tarSize) {
|
||||
// If only one disk remains to be moved from src, move it directly to tar
|
||||
// If only one disk remains on src, move it directly to tar
|
||||
if (i == 1) {
|
||||
move(src, srcSize, tar, tarSize);
|
||||
return;
|
||||
}
|
||||
// Subproblem f(i-1): move the top i-1 disks from src to buf using tar
|
||||
dfs(i - 1, src, srcSize, tar, tarSize, buf, bufSize);
|
||||
// Subproblem f(1): move the remaining disk of this subproblem from src to tar
|
||||
// Subproblem f(1): move the remaining disk from src to tar
|
||||
move(src, srcSize, tar, tarSize);
|
||||
// Subproblem f(i-1): move the top i-1 disks from buf to tar using src
|
||||
dfs(i - 1, buf, bufSize, src, srcSize, tar, tarSize);
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem */
|
||||
/* Solve the Tower of Hanoi */
|
||||
void solveHanota(int *A, int *ASize, int *B, int *BSize, int *C, int *CSize) {
|
||||
// Move the top n disks from A to C using B
|
||||
dfs(*ASize, A, ASize, B, BSize, C, CSize);
|
||||
@@ -43,7 +43,7 @@ void solveHanota(int *A, int *ASize, int *B, int *BSize, int *C, int *CSize) {
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// The end of each list represents the top of the peg
|
||||
// The end of the list is the top of the peg
|
||||
int a[] = {5, 4, 3, 2, 1};
|
||||
int b[MAX_SIZE] = {0};
|
||||
int c[MAX_SIZE] = {0};
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.c
|
||||
* Created Time: 2023-09-22
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Backtracking */
|
||||
void backtrack(int *choices, int state, int n, int *res, int len) {
|
||||
// When step n is reached, increase the number of ways by 1
|
||||
if (state == n)
|
||||
res[0]++;
|
||||
// Iterate over all choices
|
||||
for (int i = 0; i < len; i++) {
|
||||
int choice = choices[i];
|
||||
// Prune: do not go beyond step n
|
||||
if (state + choice > n)
|
||||
continue;
|
||||
// Try: make a choice and update the state
|
||||
backtrack(choices, state + choice, n, res, len);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: backtracking */
|
||||
int climbingStairsBacktrack(int n) {
|
||||
int choices[2] = {1, 2}; // Choose to climb 1 or 2 steps
|
||||
int state = 0; // Start climbing from step 0
|
||||
int *res = (int *)malloc(sizeof(int));
|
||||
*res = 0; // Use res[0] to record the number of ways
|
||||
int len = sizeof(choices) / sizeof(int);
|
||||
backtrack(choices, state, n, res, len);
|
||||
int result = *res;
|
||||
free(res);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsBacktrack(n);
|
||||
printf("Number of ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.c
|
||||
* Created Time: 2023-09-22
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Backtracking */
|
||||
void backtrack(int *choices, int state, int n, int *res, int len) {
|
||||
// Count one more way when we reach stair n
|
||||
if (state == n)
|
||||
res[0]++;
|
||||
// Iterate over all choices
|
||||
for (int i = 0; i < len; i++) {
|
||||
int choice = choices[i];
|
||||
// Prune moves that would overshoot stair n
|
||||
if (state + choice > n)
|
||||
continue;
|
||||
// Try a choice and update the state
|
||||
backtrack(choices, state + choice, n, res, len);
|
||||
// Undo the choice
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs with backtracking */
|
||||
int climbingStairsBacktrack(int n) {
|
||||
int choices[2] = {1, 2}; // Each move can climb 1 or 2 stairs
|
||||
int state = 0; // Start at stair 0
|
||||
int *res = (int *)malloc(sizeof(int));
|
||||
*res = 0; // Store the number of ways in res[0]
|
||||
int len = sizeof(choices) / sizeof(int);
|
||||
backtrack(choices, state, n, res, len);
|
||||
int result = *res;
|
||||
free(res);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsBacktrack(n);
|
||||
printf("Ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
/* Constrained stair climbing with dynamic programming */
|
||||
int climbingStairsConstraintDP(int n) {
|
||||
if (n == 1 || n == 2) {
|
||||
return 1;
|
||||
@@ -16,18 +16,18 @@ int climbingStairsConstraintDP(int n) {
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i] = calloc(3, sizeof(int));
|
||||
}
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
// Base cases: set the solutions to the smallest subproblems
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
// State transition: solve larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
}
|
||||
int res = dp[n][1] + dp[n][2];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
@@ -40,7 +40,7 @@ int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsConstraintDP(n);
|
||||
printf("Number of ways to climb %d stairs: %d\n", n, res);
|
||||
printf("Ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.c
|
||||
* Created Time: 2023-09-19
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Search */
|
||||
int dfs(int i) {
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: search */
|
||||
int climbingStairsDFS(int n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFS(n);
|
||||
printf("Number of ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
/**
|
||||
* File: climbing_stairs_dfs.c
|
||||
* Created Time: 2023-09-19
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Search */
|
||||
int dfs(int i) {
|
||||
// Return the known value for dp[1] or dp[2]
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs with search */
|
||||
int climbingStairsDFS(int n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFS(n);
|
||||
printf("Ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,44 +1,44 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.c
|
||||
* Created Time: 2023-09-19
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Memoized search */
|
||||
int dfs(int i, int *mem) {
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// If dp[i] has been recorded, return it directly
|
||||
if (mem[i] != -1)
|
||||
return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
// Record dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: memoized search */
|
||||
int climbingStairsDFSMem(int n) {
|
||||
// mem[i] stores the number of ways to reach step i; -1 means no result has been recorded
|
||||
int *mem = (int *)malloc((n + 1) * sizeof(int));
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = -1;
|
||||
}
|
||||
int result = dfs(n, mem);
|
||||
free(mem);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFSMem(n);
|
||||
printf("Number of ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.c
|
||||
* Created Time: 2023-09-19
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Memoized search */
|
||||
int dfs(int i, int *mem) {
|
||||
// Return the known value for dp[1] or dp[2]
|
||||
if (i == 1 || i == 2)
|
||||
return i;
|
||||
// Return dp[i] directly if it is cached
|
||||
if (mem[i] != -1)
|
||||
return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
int count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
// Cache dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs with memoized search */
|
||||
int climbingStairsDFSMem(int n) {
|
||||
// mem[i] stores the number of ways to reach stair i. A value of -1 means no result is cached
|
||||
int *mem = (int *)malloc((n + 1) * sizeof(int));
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = -1;
|
||||
}
|
||||
int result = dfs(n, mem);
|
||||
free(mem);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFSMem(n);
|
||||
printf("Ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,51 +1,51 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.c
|
||||
* Created Time: 2023-09-19
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Climbing stairs: dynamic programming */
|
||||
int climbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
int *dp = (int *)malloc((n + 1) * sizeof(int));
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
int result = dp[n];
|
||||
free(dp);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Climbing stairs: space-optimized dynamic programming */
|
||||
int climbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
int a = 1, b = 2;
|
||||
for (int i = 3; i <= n; i++) {
|
||||
int tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDP(n);
|
||||
printf("Number of ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
printf("Number of ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
/**
|
||||
* File: climbing_stairs_dp.c
|
||||
* Created Time: 2023-09-19
|
||||
* Author: huawuque404 (huawuque404@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Climbing stairs with dynamic programming */
|
||||
int climbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
int *dp = (int *)malloc((n + 1) * sizeof(int));
|
||||
// Base cases: set the solutions to the smallest subproblems
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: solve larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
int result = dp[n];
|
||||
free(dp);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Climbing stairs with space-optimized dynamic programming */
|
||||
int climbingStairsDPComp(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
int a = 1, b = 2;
|
||||
for (int i = 3; i <= n; i++) {
|
||||
int tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDP(n);
|
||||
printf("Ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
printf("Ways to climb %d stairs: %d\n", n, res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ int myMin(int a, int b) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/* Coin change: dynamic programming */
|
||||
/* Coin change with dynamic programming */
|
||||
int coinChangeDP(int coins[], int amt, int coinsSize) {
|
||||
int n = coinsSize;
|
||||
int MAX = amt + 1;
|
||||
@@ -20,24 +20,24 @@ int coinChangeDP(int coins[], int amt, int coinsSize) {
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i] = calloc(amt + 1, sizeof(int));
|
||||
}
|
||||
// State transitions: first row and first column
|
||||
// State transitions for the first row and column
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transitions: remaining rows and columns
|
||||
// State transitions for the remaining rows and columns
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
// Skip coin i if its value exceeds the target amount
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
// Take the minimum of the counts for skipping and taking coin i
|
||||
dp[i][a] = myMin(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[n][amt] != MAX ? dp[n][amt] : -1;
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
@@ -45,7 +45,7 @@ int coinChangeDP(int coins[], int amt, int coinsSize) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Coin change: space-optimized dynamic programming */
|
||||
/* Coin change with space-optimized dynamic programming */
|
||||
int coinChangeDPComp(int coins[], int amt, int coinsSize) {
|
||||
int n = coinsSize;
|
||||
int MAX = amt + 1;
|
||||
@@ -56,20 +56,20 @@ int coinChangeDPComp(int coins[], int amt, int coinsSize) {
|
||||
}
|
||||
dp[0] = 0;
|
||||
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
// Skip coin i if its value exceeds the target amount
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
// Take the minimum of the counts for skipping and taking coin i
|
||||
dp[a] = myMin(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[amt] != MAX ? dp[amt] : -1;
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Coin change II: dynamic programming */
|
||||
/* Coin change II with dynamic programming */
|
||||
int coinChangeIIDP(int coins[], int amt, int coinsSize) {
|
||||
int n = coinsSize;
|
||||
// Initialize the dp table
|
||||
@@ -18,20 +18,20 @@ int coinChangeIIDP(int coins[], int amt, int coinsSize) {
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
// Skip coin i if its value exceeds the target amount
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Add the numbers of ways without and with coin i
|
||||
// Add the counts for skipping and taking coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[n][amt];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
@@ -39,26 +39,26 @@ int coinChangeIIDP(int coins[], int amt, int coinsSize) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Coin change II: space-optimized dynamic programming */
|
||||
/* Coin change II with space-optimized dynamic programming */
|
||||
int coinChangeIIDPComp(int coins[], int amt, int coinsSize) {
|
||||
int n = coinsSize;
|
||||
// Initialize the dp table
|
||||
int *dp = calloc(amt + 1, sizeof(int));
|
||||
dp[0] = 1;
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
// Skip coin i if its value exceeds the target amount
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Add the numbers of ways without and with coin i
|
||||
// Add the counts for skipping and taking coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[amt];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -11,21 +11,21 @@ int myMin(int a, int b) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/* Edit distance: brute-force search */
|
||||
/* Edit distance with brute-force search */
|
||||
int editDistanceDFS(char *s, char *t, int i, int j) {
|
||||
// If both prefixes s[0:i] and t[0:j] are empty, return 0
|
||||
// Return 0 if both s and t are empty
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If the prefix s[0:i] is empty, return j, the length of t[0:j]
|
||||
// Return the length of t if s is empty
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If the prefix t[0:j] is empty, return i, the length of s[0:i]
|
||||
// Return the length of s if t is empty
|
||||
if (j == 0)
|
||||
return i;
|
||||
// If the two characters are equal, skip both of them
|
||||
// Skip both characters if they match
|
||||
if (s[i - 1] == t[j - 1])
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
// Minimum edits = 1 + the smallest remaining edit count after an insertion, deletion, or replacement
|
||||
int insert = editDistanceDFS(s, t, i, j - 1);
|
||||
int del = editDistanceDFS(s, t, i - 1, j);
|
||||
int replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
@@ -33,92 +33,92 @@ int editDistanceDFS(char *s, char *t, int i, int j) {
|
||||
return myMin(myMin(insert, del), replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: memoized search */
|
||||
/* Edit distance with memoized search */
|
||||
int editDistanceDFSMem(char *s, char *t, int memCols, int **mem, int i, int j) {
|
||||
// If both prefixes s[0:i] and t[0:j] are empty, return 0
|
||||
// Return 0 if both s and t are empty
|
||||
if (i == 0 && j == 0)
|
||||
return 0;
|
||||
// If the prefix s[0:i] is empty, return j, the length of t[0:j]
|
||||
// Return the length of t if s is empty
|
||||
if (i == 0)
|
||||
return j;
|
||||
// If the prefix t[0:j] is empty, return i, the length of s[0:i]
|
||||
// Return the length of s if t is empty
|
||||
if (j == 0)
|
||||
return i;
|
||||
// If a result has already been recorded, return it directly
|
||||
// Return the cached result if available
|
||||
if (mem[i][j] != -1)
|
||||
return mem[i][j];
|
||||
// If the two characters are equal, skip both of them
|
||||
// Skip both characters if they match
|
||||
if (s[i - 1] == t[j - 1])
|
||||
return editDistanceDFSMem(s, t, memCols, mem, i - 1, j - 1);
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
// Minimum edits = 1 + the smallest remaining edit count after an insertion, deletion, or replacement
|
||||
int insert = editDistanceDFSMem(s, t, memCols, mem, i, j - 1);
|
||||
int del = editDistanceDFSMem(s, t, memCols, mem, i - 1, j);
|
||||
int replace = editDistanceDFSMem(s, t, memCols, mem, i - 1, j - 1);
|
||||
// Record and return the minimum number of edits
|
||||
// Cache and return the minimum number of edits
|
||||
mem[i][j] = myMin(myMin(insert, del), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: dynamic programming */
|
||||
/* Edit distance with dynamic programming */
|
||||
int editDistanceDP(char *s, char *t, int n, int m) {
|
||||
int **dp = malloc((n + 1) * sizeof(int *));
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i] = calloc(m + 1, sizeof(int));
|
||||
}
|
||||
// State transitions: first row and first column
|
||||
// State transitions for the first row and column
|
||||
for (int i = 1; i <= n; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
// State transitions: remaining rows and columns
|
||||
// State transitions for the remaining rows and columns
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j <= m; j++) {
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// If the two characters are equal, skip both of them
|
||||
// Skip both characters if they match
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
// Minimum edits = 1 + the smallest remaining edit count after an insertion, deletion, or replacement
|
||||
dp[i][j] = myMin(myMin(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[n][m];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
/* Edit distance with space-optimized dynamic programming */
|
||||
int editDistanceDPComp(char *s, char *t, int n, int m) {
|
||||
int *dp = calloc(m + 1, sizeof(int));
|
||||
// State transitions: first row
|
||||
// State transitions for the first row
|
||||
for (int j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transitions: remaining rows
|
||||
// State transitions for the remaining rows
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// State transitions: first column
|
||||
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
// State transitions for the first column
|
||||
int leftup = dp[0]; // Save dp[i-1, j-1] temporarily
|
||||
dp[0] = i;
|
||||
// State transitions: remaining columns
|
||||
// State transitions for the remaining columns
|
||||
for (int j = 1; j <= m; j++) {
|
||||
int temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// If the two characters are equal, skip both of them
|
||||
// Skip both characters if they match
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
// Minimum edits = 1 + the smallest remaining edit count after an insertion, deletion, or replacement
|
||||
dp[j] = myMin(myMin(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
|
||||
leftup = temp; // Update the saved value to hold dp[i-1, j-1] for the next iteration
|
||||
}
|
||||
}
|
||||
int res = dp[m];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
@@ -141,7 +141,7 @@ int main() {
|
||||
}
|
||||
res = editDistanceDFSMem(s, t, m + 1, mem, n, m);
|
||||
printf("Changing %s to %s requires at least %d edits\n", s, t, res);
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(mem[i]);
|
||||
}
|
||||
|
||||
@@ -11,46 +11,46 @@ int myMax(int a, int b) {
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: brute-force search */
|
||||
/* 0-1 knapsack with brute-force search */
|
||||
int knapsackDFS(int wgt[], int val[], int i, int c) {
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
// Return a value of 0 if all items have been considered or no capacity remains
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
// If the item exceeds the remaining capacity, we can only skip it
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
// Compute the maximum values for skipping and taking item i
|
||||
int no = knapsackDFS(wgt, val, i - 1, c);
|
||||
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Return the larger value from the two choices
|
||||
// Return the larger of the two values
|
||||
return myMax(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: memoized search */
|
||||
/* 0-1 knapsack with memoized search */
|
||||
int knapsackDFSMem(int wgt[], int val[], int memCols, int **mem, int i, int c) {
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
// Return a value of 0 if all items have been considered or no capacity remains
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If a result has already been recorded, return it directly
|
||||
// Return the cached result if available
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
// If the item exceeds the remaining capacity, we can only skip it
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, memCols, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
// Compute the maximum values for skipping and taking item i
|
||||
int no = knapsackDFSMem(wgt, val, memCols, mem, i - 1, c);
|
||||
int yes = knapsackDFSMem(wgt, val, memCols, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Record and return the larger value from the two choices
|
||||
// Cache and return the larger of the two values
|
||||
mem[i][c] = myMax(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: dynamic programming */
|
||||
/* 0-1 knapsack with dynamic programming */
|
||||
int knapsackDP(int wgt[], int val[], int cap, int wgtSize) {
|
||||
int n = wgtSize;
|
||||
// Initialize the dp table
|
||||
@@ -58,43 +58,43 @@ int knapsackDP(int wgt[], int val[], int cap, int wgtSize) {
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i] = calloc(cap + 1, sizeof(int));
|
||||
}
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
// Skip item i if its weight exceeds the capacity
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
// Take the larger value from skipping or taking item i
|
||||
dp[i][c] = myMax(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[n][cap];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: space-optimized dynamic programming */
|
||||
/* 0-1 knapsack with space-optimized dynamic programming */
|
||||
int knapsackDPComp(int wgt[], int val[], int cap, int wgtSize) {
|
||||
int n = wgtSize;
|
||||
// Initialize the dp table
|
||||
int *dp = calloc(cap + 1, sizeof(int));
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// Traverse in decreasing order
|
||||
// Iterate in descending order
|
||||
for (int c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
// Take the larger value from skipping or taking item i
|
||||
dp[c] = myMax(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[cap];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
@@ -109,7 +109,7 @@ int main() {
|
||||
|
||||
// Brute-force search
|
||||
int res = knapsackDFS(wgt, val, n, cap);
|
||||
printf("Maximum item value within the knapsack capacity: %d\n", res);
|
||||
printf("Maximum total item value within the weight limit: %d\n", res);
|
||||
|
||||
// Memoized search
|
||||
int **mem = malloc((n + 1) * sizeof(int *));
|
||||
@@ -118,8 +118,8 @@ int main() {
|
||||
memset(mem[i], -1, (cap + 1) * sizeof(int));
|
||||
}
|
||||
res = knapsackDFSMem(wgt, val, cap + 1, mem, n, cap);
|
||||
printf("Maximum item value within the knapsack capacity: %d\n", res);
|
||||
// Free memory
|
||||
printf("Maximum total item value within the weight limit: %d\n", res);
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(mem[i]);
|
||||
}
|
||||
@@ -127,11 +127,11 @@ int main() {
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap, wgtSize);
|
||||
printf("Maximum item value within the knapsack capacity: %d\n", res);
|
||||
printf("Maximum total item value within the weight limit: %d\n", res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap, wgtSize);
|
||||
printf("Maximum item value within the knapsack capacity: %d\n", res);
|
||||
printf("Maximum total item value within the weight limit: %d\n", res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -11,27 +11,27 @@ int myMin(int a, int b) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/* Minimum cost to climb stairs: dynamic programming */
|
||||
/* Minimum cost to climb stairs with dynamic programming */
|
||||
int minCostClimbingStairsDP(int cost[], int costSize) {
|
||||
int n = costSize - 1;
|
||||
if (n == 1 || n == 2)
|
||||
return cost[n];
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
int *dp = calloc(n + 1, sizeof(int));
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
// Base cases: set the solutions to the smallest subproblems
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
// State transition: solve larger subproblems using smaller ones
|
||||
for (int i = 3; i <= n; i++) {
|
||||
dp[i] = myMin(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
int res = dp[n];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Minimum cost to climb stairs: space-optimized dynamic programming */
|
||||
/* Minimum cost to climb stairs with space-optimized dynamic programming */
|
||||
int minCostClimbingStairsDPComp(int cost[], int costSize) {
|
||||
int n = costSize - 1;
|
||||
if (n == 1 || n == 2)
|
||||
@@ -49,7 +49,7 @@ int minCostClimbingStairsDPComp(int cost[], int costSize) {
|
||||
int main() {
|
||||
int cost[] = {0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1};
|
||||
int costSize = sizeof(cost) / sizeof(cost[0]);
|
||||
printf("Input list of stair costs:");
|
||||
printf("Input stair costs: ");
|
||||
printArray(cost, costSize);
|
||||
|
||||
int res = minCostClimbingStairsDP(cost, costSize);
|
||||
|
||||
@@ -14,46 +14,46 @@ int myMin(int a, int b) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/* Minimum path sum: brute-force search */
|
||||
/* Minimum path sum with brute-force search */
|
||||
int minPathSumDFS(int grid[MAX_SIZE][MAX_SIZE], int i, int j) {
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
// Return a cost of +∞ if either index is out of bounds
|
||||
if (i < 0 || j < 0) {
|
||||
return INT_MAX;
|
||||
}
|
||||
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
|
||||
// Find the minimum path costs from the top left to (i-1, j) and (i, j-1)
|
||||
int up = minPathSumDFS(grid, i - 1, j);
|
||||
int left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
// Return the minimum path cost from the top left to (i, j)
|
||||
return myMin(left, up) != INT_MAX ? myMin(left, up) + grid[i][j] : INT_MAX;
|
||||
}
|
||||
|
||||
/* Minimum path sum: memoized search */
|
||||
/* Minimum path sum with memoized search */
|
||||
int minPathSumDFSMem(int grid[MAX_SIZE][MAX_SIZE], int mem[MAX_SIZE][MAX_SIZE], int i, int j) {
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
// Return a cost of +∞ if either index is out of bounds
|
||||
if (i < 0 || j < 0) {
|
||||
return INT_MAX;
|
||||
}
|
||||
// If a result has already been recorded, return it directly
|
||||
// Return the cached result if available
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path costs to the cells on the left and above
|
||||
// Minimum path costs for the cells to the left and above
|
||||
int up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
int left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Record and return the minimum path cost from the top-left corner to (i, j)
|
||||
// Cache and return the minimum path cost from the top left to (i, j)
|
||||
mem[i][j] = myMin(left, up) != INT_MAX ? myMin(left, up) + grid[i][j] : INT_MAX;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: dynamic programming */
|
||||
/* Minimum path sum with dynamic programming */
|
||||
int minPathSumDP(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
|
||||
// Initialize the dp table
|
||||
int **dp = malloc(n * sizeof(int *));
|
||||
@@ -61,48 +61,48 @@ int minPathSumDP(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
|
||||
dp[i] = calloc(m, sizeof(int));
|
||||
}
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transitions: first row
|
||||
// State transitions for the first row
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transitions: first column
|
||||
// State transitions for the first column
|
||||
for (int i = 1; i < n; i++) {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// State transitions: remaining rows and columns
|
||||
// State transitions for the remaining rows and columns
|
||||
for (int i = 1; i < n; i++) {
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[i][j] = myMin(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
int res = dp[n - 1][m - 1];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i < n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Minimum path sum: space-optimized dynamic programming */
|
||||
/* Minimum path sum with space-optimized dynamic programming */
|
||||
int minPathSumDPComp(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
|
||||
// Initialize the dp table
|
||||
int *dp = calloc(m, sizeof(int));
|
||||
// State transitions: first row
|
||||
// State transitions for the first row
|
||||
dp[0] = grid[0][0];
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transitions: remaining rows
|
||||
// State transitions for the remaining rows
|
||||
for (int i = 1; i < n; i++) {
|
||||
// State transitions: first column
|
||||
// State transitions for the first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transitions: remaining columns
|
||||
// State transitions for the remaining columns
|
||||
for (int j = 1; j < m; j++) {
|
||||
dp[j] = myMin(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
int res = dp[m - 1];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
@@ -110,25 +110,25 @@ int minPathSumDPComp(int grid[MAX_SIZE][MAX_SIZE], int n, int m) {
|
||||
/* Driver code */
|
||||
int main() {
|
||||
int grid[MAX_SIZE][MAX_SIZE] = {{1, 3, 1, 5}, {2, 2, 4, 2}, {5, 3, 2, 1}, {4, 3, 5, 2}};
|
||||
int n = 4, m = 4; // The matrix capacity is MAX_SIZE * MAX_SIZE; the active region has n rows and m columns
|
||||
int n = 4, m = 4; // The matrix has room for MAX_SIZE * MAX_SIZE entries, with n active rows and m active columns
|
||||
|
||||
// Brute-force search
|
||||
int res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
|
||||
printf("Minimum path sum from the top left to the bottom right: %d\n", res);
|
||||
|
||||
// Memoized search
|
||||
int mem[MAX_SIZE][MAX_SIZE];
|
||||
memset(mem, -1, sizeof(mem));
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
|
||||
printf("Minimum path sum from the top left to the bottom right: %d\n", res);
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid, n, m);
|
||||
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
|
||||
printf("Minimum path sum from the top left to the bottom right: %d\n", res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid, n, m);
|
||||
printf("Minimum path sum from the top-left to the bottom-right corner: %d\n", res);
|
||||
printf("Minimum path sum from the top left to the bottom right: %d\n", res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ int myMax(int a, int b) {
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
/* Unbounded knapsack with dynamic programming */
|
||||
int unboundedKnapsackDP(int wgt[], int val[], int cap, int wgtSize) {
|
||||
int n = wgtSize;
|
||||
// Initialize the dp table
|
||||
@@ -19,45 +19,45 @@ int unboundedKnapsackDP(int wgt[], int val[], int cap, int wgtSize) {
|
||||
for (int i = 0; i <= n; i++) {
|
||||
dp[i] = calloc(cap + 1, sizeof(int));
|
||||
}
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
// Skip item i if its weight exceeds the capacity
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
// Take the larger value from skipping or taking item i
|
||||
dp[i][c] = myMax(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[n][cap];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
for (int i = 0; i <= n; i++) {
|
||||
free(dp[i]);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: space-optimized dynamic programming */
|
||||
/* Unbounded knapsack with space-optimized dynamic programming */
|
||||
int unboundedKnapsackDPComp(int wgt[], int val[], int cap, int wgtSize) {
|
||||
int n = wgtSize;
|
||||
// Initialize the dp table
|
||||
int *dp = calloc(cap + 1, sizeof(int));
|
||||
// State transitions
|
||||
// State transition
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
// Skip item i if its weight exceeds the capacity
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
// Take the larger value from skipping or taking item i
|
||||
dp[c] = myMax(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
int res = dp[cap];
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(dp);
|
||||
return res;
|
||||
}
|
||||
@@ -71,11 +71,11 @@ int main() {
|
||||
|
||||
// Dynamic programming
|
||||
int res = unboundedKnapsackDP(wgt, val, cap, wgtSize);
|
||||
printf("Maximum item value within the knapsack capacity: %d\n", res);
|
||||
printf("Maximum total item value within the weight limit: %d\n", res);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap, wgtSize);
|
||||
printf("Maximum item value within the knapsack capacity: %d\n", res);
|
||||
printf("Maximum total item value within the weight limit: %d\n", res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume at most 100 vertices
|
||||
// Assume a maximum of 100 nodes
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Adjacency-list node structure */
|
||||
/* Node structure */
|
||||
typedef struct AdjListNode {
|
||||
Vertex *vertex; // Vertex
|
||||
struct AdjListNode *next; // Next node
|
||||
} AdjListNode;
|
||||
|
||||
/* Undirected graph structure implemented with an adjacency list */
|
||||
/* Undirected graph represented by an adjacency list */
|
||||
typedef struct {
|
||||
AdjListNode *heads[MAX_SIZE]; // Array of list heads
|
||||
int size; // Number of vertices
|
||||
AdjListNode *heads[MAX_SIZE]; // Array of nodes
|
||||
int size; // Number of nodes
|
||||
} GraphAdjList;
|
||||
|
||||
/* Constructor */
|
||||
@@ -51,7 +51,7 @@ void delGraphAdjList(GraphAdjList *graph) {
|
||||
free(graph);
|
||||
}
|
||||
|
||||
/* Find the list node corresponding to a vertex */
|
||||
/* Find the node for a vertex */
|
||||
AdjListNode *findNode(GraphAdjList *graph, Vertex *vet) {
|
||||
for (int i = 0; i < graph->size; i++) {
|
||||
if (graph->heads[i]->vertex == vet) {
|
||||
@@ -65,7 +65,7 @@ AdjListNode *findNode(GraphAdjList *graph, Vertex *vet) {
|
||||
void addEdgeHelper(AdjListNode *head, Vertex *vet) {
|
||||
AdjListNode *node = (AdjListNode *)malloc(sizeof(AdjListNode));
|
||||
node->vertex = vet;
|
||||
// Insert at the front of the neighbor list
|
||||
// Insert at the head
|
||||
node->next = head->next;
|
||||
head->next = node;
|
||||
}
|
||||
@@ -75,7 +75,7 @@ void addEdge(GraphAdjList *graph, Vertex *vet1, Vertex *vet2) {
|
||||
AdjListNode *head1 = findNode(graph, vet1);
|
||||
AdjListNode *head2 = findNode(graph, vet2);
|
||||
assert(head1 != NULL && head2 != NULL && head1 != head2);
|
||||
// Add edge vet1 - vet2
|
||||
// Add the edge vet1 - vet2
|
||||
addEdgeHelper(head1, vet2);
|
||||
addEdgeHelper(head2, vet1);
|
||||
}
|
||||
@@ -93,7 +93,7 @@ void removeEdgeHelper(AdjListNode *head, Vertex *vet) {
|
||||
return;
|
||||
// Remove the node corresponding to vet from the linked list
|
||||
pre->next = cur->next;
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(cur);
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ void removeEdge(GraphAdjList *graph, Vertex *vet1, Vertex *vet2) {
|
||||
AdjListNode *head1 = findNode(graph, vet1);
|
||||
AdjListNode *head2 = findNode(graph, vet2);
|
||||
assert(head1 != NULL && head2 != NULL);
|
||||
// Remove edge vet1 - vet2
|
||||
// Remove the edge vet1 - vet2
|
||||
removeEdgeHelper(head1, head2->vertex);
|
||||
removeEdgeHelper(head2, head1->vertex);
|
||||
}
|
||||
@@ -116,7 +116,7 @@ void addVertex(GraphAdjList *graph, Vertex *vet) {
|
||||
AdjListNode *head = (AdjListNode *)malloc(sizeof(AdjListNode));
|
||||
head->vertex = vet;
|
||||
head->next = NULL;
|
||||
// Add a new list to the adjacency list
|
||||
// Add a new linked list to the adjacency list
|
||||
graph->heads[graph->size++] = head;
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ void addVertex(GraphAdjList *graph, Vertex *vet) {
|
||||
void removeVertex(GraphAdjList *graph, Vertex *vet) {
|
||||
AdjListNode *node = findNode(graph, vet);
|
||||
assert(node != NULL);
|
||||
// Shift subsequent vertices forward to fill the gap
|
||||
// Shift the following vertices forward to fill the gap
|
||||
int i;
|
||||
for (i = 0; i < graph->size; i++) {
|
||||
if (graph->heads[i] == node)
|
||||
@@ -134,7 +134,7 @@ void removeVertex(GraphAdjList *graph, Vertex *vet) {
|
||||
graph->heads[j] = graph->heads[j + 1];
|
||||
}
|
||||
graph->size--;
|
||||
// Traverse the lists of the other vertices and remove all edges incident to vet
|
||||
// Traverse the other vertices' lists and remove every edge incident to vet
|
||||
for (int i = 0; i < graph->size; i++) {
|
||||
AdjListNode *cur = graph->heads[i];
|
||||
while (cur->next != NULL) {
|
||||
@@ -147,7 +147,7 @@ void removeVertex(GraphAdjList *graph, Vertex *vet) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Remove the list corresponding to vertex vet from the adjacency list
|
||||
// Remove the linked list for vertex vet from the adjacency list
|
||||
while (node != NULL) {
|
||||
AdjListNode *next = node->next;
|
||||
free(node);
|
||||
|
||||
@@ -25,13 +25,13 @@ int main() {
|
||||
printGraph(graph);
|
||||
|
||||
/* Add an edge */
|
||||
// Vertices 1 and 2 are v[0] and v[2]
|
||||
// Vertices 1 and 2 are v[0] and v[2], respectively
|
||||
addEdge(graph, v[0], v[2]);
|
||||
printf("\nGraph after adding edge 1-2:\n");
|
||||
printGraph(graph);
|
||||
|
||||
/* Remove an edge */
|
||||
// Vertices 1 and 3 are v[0] and v[1]
|
||||
// Vertices 1 and 3 are v[0] and v[1], respectively
|
||||
removeEdge(graph, v[0], v[1]);
|
||||
printf("\nGraph after removing edge 1-3:\n");
|
||||
printGraph(graph);
|
||||
@@ -48,7 +48,7 @@ int main() {
|
||||
printf("\nGraph after removing vertex 3:\n");
|
||||
printGraph(graph);
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
delGraphAdjList(graph);
|
||||
free(v);
|
||||
return 0;
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
// Assume at most 100 vertices
|
||||
// Assume a maximum of 100 vertices
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Undirected graph structure implemented with an adjacency matrix */
|
||||
/* Structure for an undirected graph represented by an adjacency matrix */
|
||||
typedef struct {
|
||||
int vertices[MAX_SIZE];
|
||||
int adjMat[MAX_SIZE][MAX_SIZE];
|
||||
@@ -39,7 +39,7 @@ void addVertex(GraphAdjMat *graph, int val) {
|
||||
fprintf(stderr, "The graph has reached its maximum number of vertices\n");
|
||||
return;
|
||||
}
|
||||
// Add the vertex at index n and set row n and column n to zero
|
||||
// Add the nth vertex and set row n and column n to zero
|
||||
int n = graph->size;
|
||||
graph->vertices[n] = val;
|
||||
for (int i = 0; i <= n; i++) {
|
||||
@@ -54,17 +54,17 @@ void removeVertex(GraphAdjMat *graph, int index) {
|
||||
fprintf(stderr, "Vertex index out of bounds\n");
|
||||
return;
|
||||
}
|
||||
// Remove the vertex at index `index` from the vertex list
|
||||
// Remove the vertex at the specified index from the vertex list
|
||||
for (int i = index; i < graph->size - 1; i++) {
|
||||
graph->vertices[i] = graph->vertices[i + 1];
|
||||
}
|
||||
// Remove row `index` from the adjacency matrix
|
||||
// Remove the row at the specified index from the adjacency matrix
|
||||
for (int i = index; i < graph->size - 1; i++) {
|
||||
for (int j = 0; j < graph->size; j++) {
|
||||
graph->adjMat[i][j] = graph->adjMat[i + 1][j];
|
||||
}
|
||||
}
|
||||
// Remove column `index` from the adjacency matrix
|
||||
// Remove the column at the specified index from the adjacency matrix
|
||||
for (int i = 0; i < graph->size; i++) {
|
||||
for (int j = index; j < graph->size - 1; j++) {
|
||||
graph->adjMat[i][j] = graph->adjMat[i][j + 1];
|
||||
@@ -74,7 +74,7 @@ void removeVertex(GraphAdjMat *graph, int index) {
|
||||
}
|
||||
|
||||
/* Add an edge */
|
||||
// Parameters i and j are element indices in vertices
|
||||
// Parameters i and j are indices into vertices
|
||||
void addEdge(GraphAdjMat *graph, int i, int j) {
|
||||
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
|
||||
fprintf(stderr, "Edge endpoint indices are out of bounds or equal\n");
|
||||
@@ -85,7 +85,7 @@ void addEdge(GraphAdjMat *graph, int i, int j) {
|
||||
}
|
||||
|
||||
/* Remove an edge */
|
||||
// Parameters i and j are element indices in vertices
|
||||
// Parameters i and j are indices into vertices
|
||||
void removeEdge(GraphAdjMat *graph, int i, int j) {
|
||||
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
|
||||
fprintf(stderr, "Edge endpoint indices are out of bounds or equal\n");
|
||||
@@ -107,7 +107,7 @@ void printGraphAdjMat(GraphAdjMat *graph) {
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Initialize the undirected graph
|
||||
// Initialize an undirected graph
|
||||
GraphAdjMat *graph = newGraphAdjMat();
|
||||
int vertices[] = {1, 3, 2, 5, 4};
|
||||
for (int i = 0; i < 5; i++) {
|
||||
@@ -143,7 +143,7 @@ int main() {
|
||||
printf("\nGraph after removing vertex 3:\n");
|
||||
printGraphAdjMat(graph);
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
delGraphAdjMat(graph);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
|
||||
#include "graph_adjacency_list.c"
|
||||
|
||||
// Assume at most 100 vertices
|
||||
// Assume a maximum of 100 nodes
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Vertex queue structure */
|
||||
/* Node queue structure */
|
||||
typedef struct {
|
||||
Vertex *vertices[MAX_SIZE];
|
||||
int front, rear, size;
|
||||
@@ -27,14 +27,14 @@ int isEmpty(Queue *q) {
|
||||
return q->size == 0;
|
||||
}
|
||||
|
||||
/* Enqueue operation */
|
||||
/* Enqueue */
|
||||
void enqueue(Queue *q, Vertex *vet) {
|
||||
q->vertices[q->rear] = vet;
|
||||
q->rear = (q->rear + 1) % MAX_SIZE;
|
||||
q->size++;
|
||||
}
|
||||
|
||||
/* Dequeue operation */
|
||||
/* Dequeue */
|
||||
Vertex *dequeue(Queue *q) {
|
||||
Vertex *vet = q->vertices[q->front];
|
||||
q->front = (q->front + 1) % MAX_SIZE;
|
||||
@@ -44,7 +44,7 @@ Vertex *dequeue(Queue *q) {
|
||||
|
||||
/* Check whether a vertex has been visited */
|
||||
int isVisited(Vertex **visited, int size, Vertex *vet) {
|
||||
// Search for the vertex with a linear scan in O(n) time
|
||||
// Scan for the node in O(n) time
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (visited[i] == vet)
|
||||
return 1;
|
||||
@@ -53,34 +53,34 @@ int isVisited(Vertex **visited, int size, Vertex *vet) {
|
||||
}
|
||||
|
||||
/* Breadth-first traversal */
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
// Represent the graph with an adjacency list to look up all neighbors of a given vertex
|
||||
void graphBFS(GraphAdjList *graph, Vertex *startVet, Vertex **res, int *resSize, Vertex **visited, int *visitedSize) {
|
||||
// Use a queue to implement BFS
|
||||
// Use a queue for BFS
|
||||
Queue *queue = newQueue();
|
||||
enqueue(queue, startVet);
|
||||
visited[(*visitedSize)++] = startVet;
|
||||
// Starting from startVet, continue until all reachable vertices have been visited
|
||||
// Starting at vertex vet, loop until all reachable vertices have been visited
|
||||
while (!isEmpty(queue)) {
|
||||
Vertex *vet = dequeue(queue); // Dequeue the front vertex
|
||||
res[(*resSize)++] = vet; // Record the visited vertex
|
||||
// Traverse all neighbors of this vertex
|
||||
// Iterate over all neighbors of this vertex
|
||||
AdjListNode *node = findNode(graph, vet);
|
||||
while (node != NULL) {
|
||||
// Skip vertices that have already been visited
|
||||
// Skip visited vertices
|
||||
if (!isVisited(visited, *visitedSize, node->vertex)) {
|
||||
enqueue(queue, node->vertex); // Enqueue only unvisited vertices
|
||||
visited[(*visitedSize)++] = node->vertex; // Mark this vertex as visited
|
||||
visited[(*visitedSize)++] = node->vertex; // Mark the vertex as visited
|
||||
}
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(queue);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Initialize the undirected graph
|
||||
// Initialize an undirected graph
|
||||
int vals[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
|
||||
int size = sizeof(vals) / sizeof(vals[0]);
|
||||
Vertex **v = valsToVets(vals, size);
|
||||
@@ -99,17 +99,17 @@ int main() {
|
||||
printGraph(graph);
|
||||
|
||||
// Breadth-first traversal
|
||||
// Vertex traversal sequence
|
||||
// Vertex traversal order
|
||||
Vertex *res[MAX_SIZE];
|
||||
int resSize = 0;
|
||||
// Track vertices that have already been visited
|
||||
// Track visited vertices
|
||||
Vertex *visited[MAX_SIZE];
|
||||
int visitedSize = 0;
|
||||
graphBFS(graph, v[0], res, &resSize, visited, &visitedSize);
|
||||
printf("\nVertex sequence from breadth-first traversal (BFS):\n");
|
||||
printf("\nBreadth-first search (BFS) visits the vertices in this order:\n");
|
||||
printArray(vetsToVals(res, resSize), resSize);
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
delGraphAdjList(graph);
|
||||
free(v);
|
||||
return 0;
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "graph_adjacency_list.c"
|
||||
|
||||
// Assume at most 100 vertices
|
||||
// Assume a maximum of 100 nodes
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Check whether a vertex has been visited */
|
||||
int isVisited(Vertex **res, int size, Vertex *vet) {
|
||||
// Search for the vertex with a linear scan in O(n) time
|
||||
// Scan for the node in O(n) time
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (res[i] == vet) {
|
||||
return 1;
|
||||
@@ -20,16 +20,16 @@ int isVisited(Vertex **res, int size, Vertex *vet) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Depth-first traversal helper function */
|
||||
/* Helper for depth-first traversal */
|
||||
void dfs(GraphAdjList *graph, Vertex **res, int *resSize, Vertex *vet) {
|
||||
// Record the visited vertex
|
||||
res[(*resSize)++] = vet;
|
||||
// Traverse all neighbors of this vertex
|
||||
// Iterate over all neighbors of this vertex
|
||||
AdjListNode *node = findNode(graph, vet);
|
||||
while (node != NULL) {
|
||||
// Skip vertices that have already been visited
|
||||
// Skip visited vertices
|
||||
if (!isVisited(res, *resSize, node->vertex)) {
|
||||
// Recursively visit the neighboring vertex
|
||||
// Visit neighbors recursively
|
||||
dfs(graph, res, resSize, node->vertex);
|
||||
}
|
||||
node = node->next;
|
||||
@@ -37,14 +37,14 @@ void dfs(GraphAdjList *graph, Vertex **res, int *resSize, Vertex *vet) {
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
// Represent the graph with an adjacency list to look up all neighbors of a given vertex
|
||||
void graphDFS(GraphAdjList *graph, Vertex *startVet, Vertex **res, int *resSize) {
|
||||
dfs(graph, res, resSize, startVet);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Initialize the undirected graph
|
||||
// Initialize an undirected graph
|
||||
int vals[] = {0, 1, 2, 3, 4, 5, 6};
|
||||
int size = sizeof(vals) / sizeof(vals[0]);
|
||||
Vertex **v = valsToVets(vals, size);
|
||||
@@ -65,10 +65,10 @@ int main() {
|
||||
Vertex *res[MAX_SIZE];
|
||||
int resSize = 0;
|
||||
graphDFS(graph, v[0], res, &resSize);
|
||||
printf("\nVertex sequence from depth-first traversal (DFS):\n");
|
||||
printf("\nDepth-first search (DFS) visits the vertices in this order:\n");
|
||||
printArray(vetsToVals(res, resSize), resSize);
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
delGraphAdjList(graph);
|
||||
free(v);
|
||||
return 0;
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Coin change: greedy algorithm */
|
||||
/* Greedy coin change */
|
||||
int coinChangeGreedy(int *coins, int size, int amt) {
|
||||
// Assume the coins list is sorted
|
||||
int i = size - 1;
|
||||
int count = 0;
|
||||
// Repeatedly make greedy choices until no amount remains
|
||||
// Make greedy choices until no amount remains
|
||||
while (amt > 0) {
|
||||
// Find the largest coin no greater than the remaining amount
|
||||
// Find the largest denomination that does not exceed the remaining amount
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
@@ -27,33 +27,33 @@ int coinChangeGreedy(int *coins, int size, int amt) {
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Greedy algorithm: guaranteed to find a globally optimal solution
|
||||
// Greedy choices are guaranteed to give a global optimum here
|
||||
int coins1[6] = {1, 5, 10, 20, 50, 100};
|
||||
int amt = 186;
|
||||
int res = coinChangeGreedy(coins1, 6, amt);
|
||||
printf("\ncoins = ");
|
||||
printArray(coins1, 6);
|
||||
printf("amt = %d\n", amt);
|
||||
printf("Greedy coin count for amount %d: %d\n", amt, res);
|
||||
printf("The minimum number of coins needed to make %d is %d\n", amt, res);
|
||||
|
||||
// Greedy algorithm: not guaranteed to find a globally optimal solution
|
||||
// Greedy choices do not guarantee a global optimum here
|
||||
int coins2[3] = {1, 20, 50};
|
||||
amt = 60;
|
||||
res = coinChangeGreedy(coins2, 3, amt);
|
||||
printf("\ncoins = ");
|
||||
printArray(coins2, 3);
|
||||
printf("amt = %d\n", amt);
|
||||
printf("Greedy coin count for amount %d: %d\n", amt, res);
|
||||
printf("The minimum number of coins needed to make %d is %d\n", amt, res);
|
||||
printf("The actual minimum is 3 coins: 20 + 20 + 20\n");
|
||||
|
||||
// Greedy algorithm: not guaranteed to find a globally optimal solution
|
||||
// Greedy choices do not guarantee a global optimum here
|
||||
int coins3[3] = {1, 49, 50};
|
||||
amt = 98;
|
||||
res = coinChangeGreedy(coins3, 3, amt);
|
||||
printf("\ncoins = ");
|
||||
printArray(coins3, 3);
|
||||
printf("amt = %d\n", amt);
|
||||
printf("Greedy coin count for amount %d: %d\n", amt, res);
|
||||
printf("The minimum number of coins needed to make %d is %d\n", amt, res);
|
||||
printf("The actual minimum is 2 coins: 49 + 49\n");
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -12,31 +12,31 @@ typedef struct {
|
||||
int v; // Item value
|
||||
} Item;
|
||||
|
||||
/* Sort by value per unit weight */
|
||||
/* Sort by value per unit of weight */
|
||||
int sortByValueDensity(const void *a, const void *b) {
|
||||
Item *t1 = (Item *)a;
|
||||
Item *t2 = (Item *)b;
|
||||
return (float)(t1->v) / t1->w < (float)(t2->v) / t2->w;
|
||||
}
|
||||
|
||||
/* Fractional knapsack: greedy algorithm */
|
||||
/* Greedy fractional knapsack */
|
||||
float fractionalKnapsack(int wgt[], int val[], int itemCount, int cap) {
|
||||
// Create a list of items, each with two attributes: weight and value
|
||||
// Create a list of items, each with a weight and a value
|
||||
Item *items = malloc(sizeof(Item) * itemCount);
|
||||
for (int i = 0; i < itemCount; i++) {
|
||||
items[i] = (Item){.w = wgt[i], .v = val[i]};
|
||||
}
|
||||
// Sort by value per unit weight, item.v / item.w, in descending order
|
||||
// Sort by value per unit of weight, item.v / item.w, in descending order
|
||||
qsort(items, (size_t)itemCount, sizeof(Item), sortByValueDensity);
|
||||
// Repeatedly make greedy choices
|
||||
// Make greedy choices in a loop
|
||||
float res = 0.0;
|
||||
for (int i = 0; i < itemCount; i++) {
|
||||
if (items[i].w <= cap) {
|
||||
// If enough capacity remains, put the entire current item in the knapsack
|
||||
// If the whole item fits, put it in the knapsack
|
||||
res += items[i].v;
|
||||
cap -= items[i].w;
|
||||
} else {
|
||||
// If the remaining capacity is insufficient, put part of the current item in the knapsack
|
||||
// If the whole item does not fit, take a fraction of it
|
||||
res += (float)cap / items[i].w * items[i].v;
|
||||
cap = 0;
|
||||
break;
|
||||
@@ -54,7 +54,7 @@ int main(void) {
|
||||
|
||||
// Greedy algorithm
|
||||
float res = fractionalKnapsack(wgt, val, sizeof(wgt) / sizeof(int), capacity);
|
||||
printf("Maximum item value within the knapsack capacity: %0.2f\n", res);
|
||||
printf("The maximum total value within the weight limit is %0.2f\n", res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -15,19 +15,19 @@ int myMax(int a, int b) {
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
/* Maximum container capacity: greedy algorithm */
|
||||
/* Greedy maximum capacity algorithm */
|
||||
int maxCapacity(int ht[], int htLength) {
|
||||
// Initialize i and j at opposite ends of the array
|
||||
// Start i and j at opposite ends of the array
|
||||
int i = 0;
|
||||
int j = htLength - 1;
|
||||
// The initial maximum capacity is 0
|
||||
int res = 0;
|
||||
// Repeatedly make greedy choices until the two sides meet
|
||||
// Make greedy choices until the two pointers meet
|
||||
while (i < j) {
|
||||
// Update the maximum capacity
|
||||
int capacity = myMin(ht[i], ht[j]) * (j - i);
|
||||
res = myMax(res, capacity);
|
||||
// Move the shorter side inward
|
||||
// Move the pointer at the shorter board inward
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
@@ -43,7 +43,7 @@ int main(void) {
|
||||
|
||||
// Greedy algorithm
|
||||
int res = maxCapacity(ht, sizeof(ht) / sizeof(int));
|
||||
printf("Maximum capacity: %d\n", res);
|
||||
printf("The maximum capacity is %d\n", res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,24 +6,24 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Maximum product after splitting: greedy algorithm */
|
||||
/* Greedy maximum product algorithm */
|
||||
int maxProductCutting(int n) {
|
||||
// When n <= 3, one part must be 1
|
||||
// When n <= 3, one piece must be 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// Greedily split off parts of size 3; a is the number of 3s and b is the remainder
|
||||
// Greedily cut off pieces of size 3. Let a be their count and b the remainder
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// When the remainder is 1, replace one pair 1 * 3 with 2 * 2
|
||||
// If the remainder is 1, replace one pair 1 * 3 with 2 * 2
|
||||
return pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// When the remainder is 2, no adjustment is needed
|
||||
// If the remainder is 2, leave it as is
|
||||
return pow(3, a) * 2;
|
||||
}
|
||||
// When the remainder is 0, no adjustment is needed
|
||||
// If the remainder is 0, no adjustment is needed
|
||||
return pow(3, a);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ int main(void) {
|
||||
int n = 58;
|
||||
// Greedy algorithm
|
||||
int res = maxProductCutting(n);
|
||||
printf("Maximum product after splitting: %d\n", res);
|
||||
printf("The maximum product after cutting is %d\n", res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/* Default hash table size */
|
||||
#define MAX_SIZE 100
|
||||
|
||||
/* Key-value pair: int -> string */
|
||||
/* Key-value pair: int->string */
|
||||
typedef struct {
|
||||
int key;
|
||||
char *val;
|
||||
@@ -21,7 +21,7 @@ typedef struct {
|
||||
int len;
|
||||
} MapSet;
|
||||
|
||||
/* Hash table implemented with an array */
|
||||
/* Array-based hash table */
|
||||
typedef struct {
|
||||
Pair *buckets[MAX_SIZE];
|
||||
} ArrayHashMap;
|
||||
@@ -52,7 +52,7 @@ int hashFunc(int key) {
|
||||
return index;
|
||||
}
|
||||
|
||||
/* Lookup operation */
|
||||
/* Look up a value */
|
||||
const char *get(const ArrayHashMap *hmap, const int key) {
|
||||
int index = hashFunc(key);
|
||||
const Pair *Pair = hmap->buckets[index];
|
||||
@@ -61,7 +61,7 @@ const char *get(const ArrayHashMap *hmap, const int key) {
|
||||
return Pair->val;
|
||||
}
|
||||
|
||||
/* Insert operation */
|
||||
/* Insert a key-value pair */
|
||||
void put(ArrayHashMap *hmap, const int key, const char *val) {
|
||||
Pair *pair = malloc(sizeof(Pair));
|
||||
pair->key = key;
|
||||
@@ -72,7 +72,7 @@ void put(ArrayHashMap *hmap, const int key, const char *val) {
|
||||
hmap->buckets[index] = pair;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
/* Remove a key-value pair */
|
||||
void removeItem(ArrayHashMap *hmap, const int key) {
|
||||
int index = hashFunc(key);
|
||||
free(hmap->buckets[index]->val);
|
||||
@@ -85,7 +85,7 @@ void pairSet(ArrayHashMap *hmap, MapSet *set) {
|
||||
Pair *entries;
|
||||
int i = 0, index = 0;
|
||||
int total = 0;
|
||||
/* Count stored key-value pairs */
|
||||
/* Count the occupied entries */
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
total++;
|
||||
@@ -109,7 +109,7 @@ void keySet(ArrayHashMap *hmap, MapSet *set) {
|
||||
int *keys;
|
||||
int i = 0, index = 0;
|
||||
int total = 0;
|
||||
/* Count stored key-value pairs */
|
||||
/* Count the occupied entries */
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
total++;
|
||||
@@ -131,7 +131,7 @@ void valueSet(ArrayHashMap *hmap, MapSet *set) {
|
||||
char **vals;
|
||||
int i = 0, index = 0;
|
||||
int total = 0;
|
||||
/* Count stored key-value pairs */
|
||||
/* Count the occupied entries */
|
||||
for (i = 0; i < MAX_SIZE; i++) {
|
||||
if (hmap->buckets[i] != NULL) {
|
||||
total++;
|
||||
@@ -165,38 +165,38 @@ int main() {
|
||||
/* Initialize the hash table */
|
||||
ArrayHashMap *hmap = newArrayHashMap();
|
||||
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
put(hmap, 12836, "小哈");
|
||||
put(hmap, 15937, "小啰");
|
||||
put(hmap, 16750, "小算");
|
||||
put(hmap, 13276, "小法");
|
||||
put(hmap, 10583, "小鸭");
|
||||
/* Insert a key-value pair */
|
||||
// Insert the pair (key, value) into the hash table
|
||||
put(hmap, 12836, "Xiao Ha");
|
||||
put(hmap, 15937, "Xiao Luo");
|
||||
put(hmap, 16750, "Xiao Suan");
|
||||
put(hmap, 13276, "Xiao Fa");
|
||||
put(hmap, 10583, "Xiao Ya");
|
||||
printf("\nHash table after insertion:\nKey -> Value\n");
|
||||
print(hmap);
|
||||
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
/* Look up a value */
|
||||
// Look up key in the hash table to get value
|
||||
const char *name = get(hmap, 15937);
|
||||
printf("\nLook up student ID 15937; name found: %s\n", name);
|
||||
printf("\nName for student ID 15937: %s\n", name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
/* Remove a key-value pair */
|
||||
// Remove the pair (key, value) from the hash table
|
||||
removeItem(hmap, 10583);
|
||||
printf("\nHash table after removing 10583:\nKey -> Value\n");
|
||||
print(hmap);
|
||||
|
||||
/* Traverse the hash table */
|
||||
/* Iterate over the hash table */
|
||||
int i;
|
||||
|
||||
printf("\nIterate over key-value pairs, Key->Value\n");
|
||||
printf("\nIterate over key-value pairs (Key->Value)\n");
|
||||
print(hmap);
|
||||
|
||||
MapSet set;
|
||||
|
||||
keySet(hmap, &set);
|
||||
int *keys = (int *)set.set;
|
||||
printf("\nIterate over keys only, Key\n");
|
||||
printf("\nIterate over keys only\n");
|
||||
for (i = 0; i < set.len; i++) {
|
||||
printf("%d\n", keys[i]);
|
||||
}
|
||||
@@ -204,7 +204,7 @@ int main() {
|
||||
|
||||
valueSet(hmap, &set);
|
||||
char **vals = (char **)set.set;
|
||||
printf("\nIterate over values only, Value\n");
|
||||
printf("\nIterate over values only\n");
|
||||
for (i = 0; i < set.len; i++) {
|
||||
printf("%s\n", vals[i]);
|
||||
}
|
||||
|
||||
@@ -23,12 +23,12 @@ typedef struct Node {
|
||||
struct Node *next;
|
||||
} Node;
|
||||
|
||||
/* Hash table with separate chaining */
|
||||
/* Hash table with chaining */
|
||||
typedef struct {
|
||||
int size; // Number of key-value pairs
|
||||
int capacity; // Hash table capacity
|
||||
double loadThres; // Load factor threshold that triggers capacity growth
|
||||
int extendRatio; // Capacity growth factor
|
||||
double loadThres; // Load factor threshold for resizing
|
||||
int extendRatio; // Growth factor
|
||||
Node **buckets; // Bucket array
|
||||
} HashMapChaining;
|
||||
|
||||
@@ -71,10 +71,10 @@ double loadFactor(HashMapChaining *hashMap) {
|
||||
return (double)hashMap->size / (double)hashMap->capacity;
|
||||
}
|
||||
|
||||
/* Lookup operation */
|
||||
/* Look up a value */
|
||||
char *get(HashMapChaining *hashMap, int key) {
|
||||
int index = hashFunc(hashMap, key);
|
||||
// Traverse the bucket; if key is found, return its corresponding val
|
||||
// Scan the bucket and return the corresponding val if key is found
|
||||
Node *cur = hashMap->buckets[index];
|
||||
while (cur) {
|
||||
if (cur->pair->key == key) {
|
||||
@@ -82,32 +82,32 @@ char *get(HashMapChaining *hashMap, int key) {
|
||||
}
|
||||
cur = cur->next;
|
||||
}
|
||||
return ""; // Return an empty string if key is not found
|
||||
return ""; // Return an empty string if key is absent
|
||||
}
|
||||
|
||||
/* Insert operation */
|
||||
/* Insert a key-value pair */
|
||||
void put(HashMapChaining *hashMap, int key, const char *val);
|
||||
|
||||
/* Grow the hash table capacity */
|
||||
/* Expand the hash table */
|
||||
void extend(HashMapChaining *hashMap) {
|
||||
// Keep a reference to the original hash table
|
||||
// Save the original hash table
|
||||
int oldCapacity = hashMap->capacity;
|
||||
Node **oldBuckets = hashMap->buckets;
|
||||
// Initialize a new hash table with the expanded capacity
|
||||
// Initialize the larger hash table
|
||||
hashMap->capacity *= hashMap->extendRatio;
|
||||
hashMap->buckets = (Node **)malloc(hashMap->capacity * sizeof(Node *));
|
||||
for (int i = 0; i < hashMap->capacity; i++) {
|
||||
hashMap->buckets[i] = NULL;
|
||||
}
|
||||
hashMap->size = 0;
|
||||
// Move the key-value pairs from the original hash table to the new one
|
||||
// Move the key-value pairs from the old table into the new one
|
||||
for (int i = 0; i < oldCapacity; i++) {
|
||||
Node *cur = oldBuckets[i];
|
||||
while (cur) {
|
||||
put(hashMap, cur->pair->key, cur->pair->val);
|
||||
Node *temp = cur;
|
||||
cur = cur->next;
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(temp->pair);
|
||||
free(temp);
|
||||
}
|
||||
@@ -116,14 +116,14 @@ void extend(HashMapChaining *hashMap) {
|
||||
free(oldBuckets);
|
||||
}
|
||||
|
||||
/* Insert operation */
|
||||
/* Insert a key-value pair */
|
||||
void put(HashMapChaining *hashMap, int key, const char *val) {
|
||||
// Grow the capacity when the load factor exceeds the threshold
|
||||
// Expand the table when the load factor exceeds the threshold
|
||||
if (loadFactor(hashMap) > hashMap->loadThres) {
|
||||
extend(hashMap);
|
||||
}
|
||||
int index = hashFunc(hashMap, key);
|
||||
// Traverse the bucket; if the specified key is found, update its val and return
|
||||
// Scan the bucket. If the specified key is found, update its val and return
|
||||
Node *cur = hashMap->buckets[index];
|
||||
while (cur) {
|
||||
if (cur->pair->key == key) {
|
||||
@@ -132,7 +132,7 @@ void put(HashMapChaining *hashMap, int key, const char *val) {
|
||||
}
|
||||
cur = cur->next;
|
||||
}
|
||||
// If key is absent, add the key-value pair at the head of the linked list
|
||||
// If key is absent, insert the pair at the head of the list
|
||||
Pair *newPair = (Pair *)malloc(sizeof(Pair));
|
||||
newPair->key = key;
|
||||
strcpy(newPair->val, val);
|
||||
@@ -143,20 +143,20 @@ void put(HashMapChaining *hashMap, int key, const char *val) {
|
||||
hashMap->size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
/* Remove a key-value pair */
|
||||
void removeItem(HashMapChaining *hashMap, int key) {
|
||||
int index = hashFunc(hashMap, key);
|
||||
Node *cur = hashMap->buckets[index];
|
||||
Node *pre = NULL;
|
||||
while (cur) {
|
||||
if (cur->pair->key == key) {
|
||||
// Remove the key-value pair from the list
|
||||
// Remove the pair from the list
|
||||
if (pre) {
|
||||
pre->next = cur->next;
|
||||
} else {
|
||||
hashMap->buckets[index] = cur->next;
|
||||
}
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(cur->pair);
|
||||
free(cur);
|
||||
hashMap->size--;
|
||||
@@ -185,28 +185,28 @@ int main() {
|
||||
/* Initialize the hash table */
|
||||
HashMapChaining *hashMap = newHashMapChaining();
|
||||
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
put(hashMap, 12836, "小哈");
|
||||
put(hashMap, 15937, "小啰");
|
||||
put(hashMap, 16750, "小算");
|
||||
put(hashMap, 13276, "小法");
|
||||
put(hashMap, 10583, "小鸭");
|
||||
/* Insert a key-value pair */
|
||||
// Insert the pair (key, value) into the hash table
|
||||
put(hashMap, 12836, "Xiao Ha");
|
||||
put(hashMap, 15937, "Xiao Luo");
|
||||
put(hashMap, 16750, "Xiao Suan");
|
||||
put(hashMap, 13276, "Xiao Fa");
|
||||
put(hashMap, 10583, "Xiao Ya");
|
||||
printf("\nHash table after insertion:\nKey -> Value\n");
|
||||
print(hashMap);
|
||||
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
/* Look up a value */
|
||||
// Look up key in the hash table to get value
|
||||
char *name = get(hashMap, 13276);
|
||||
printf("\nLook up student ID 13276; name found: %s\n", name);
|
||||
printf("\nName for student ID 13276: %s\n", name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
/* Remove a key-value pair */
|
||||
// Remove the pair (key, value) from the hash table
|
||||
removeItem(hashMap, 12836);
|
||||
printf("\nHash table after removing student ID 12836:\nKey -> Value\n");
|
||||
print(hashMap);
|
||||
|
||||
/* Free the hash table's memory */
|
||||
/* Free the memory used by the hash table */
|
||||
delHashMapChaining(hashMap);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Key-value pair */
|
||||
/* Hash table with open addressing */
|
||||
typedef struct {
|
||||
int key;
|
||||
char *val;
|
||||
@@ -16,13 +16,13 @@ typedef struct {
|
||||
typedef struct {
|
||||
int size; // Number of key-value pairs
|
||||
int capacity; // Hash table capacity
|
||||
double loadThres; // Load factor threshold that triggers capacity growth
|
||||
int extendRatio; // Capacity growth factor
|
||||
double loadThres; // Load factor threshold for resizing
|
||||
int extendRatio; // Growth factor
|
||||
Pair **buckets; // Bucket array
|
||||
Pair *TOMBSTONE; // Tombstone marker
|
||||
Pair *TOMBSTONE; // Deletion marker
|
||||
} HashMapOpenAddressing;
|
||||
|
||||
// Function declaration
|
||||
// Function declarations
|
||||
void extend(HashMapOpenAddressing *hashMap);
|
||||
|
||||
/* Constructor */
|
||||
@@ -72,46 +72,46 @@ int findBucket(HashMapOpenAddressing *hashMap, int key) {
|
||||
while (hashMap->buckets[index] != NULL) {
|
||||
// If key is found, return its bucket index
|
||||
if (hashMap->buckets[index]->key == key) {
|
||||
// If a tombstone was encountered earlier, move the key-value pair to that index
|
||||
// If a deletion marker was found earlier, move the pair to that index
|
||||
if (firstTombstone != -1) {
|
||||
hashMap->buckets[firstTombstone] = hashMap->buckets[index];
|
||||
hashMap->buckets[index] = hashMap->TOMBSTONE;
|
||||
return firstTombstone; // Return the bucket index after the move
|
||||
return firstTombstone; // Return the new bucket index
|
||||
}
|
||||
return index; // Return the bucket index
|
||||
}
|
||||
// Record the first tombstone encountered
|
||||
// Record the first deletion marker encountered
|
||||
if (firstTombstone == -1 && hashMap->buckets[index] == hashMap->TOMBSTONE) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// Calculate the bucket index, wrapping to the beginning after the end
|
||||
// Compute the next bucket index, wrapping to the start at the end
|
||||
index = (index + 1) % hashMap->capacity;
|
||||
}
|
||||
// If key is absent, return the index for insertion
|
||||
return firstTombstone == -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* Lookup operation */
|
||||
/* Look up a value */
|
||||
char *get(HashMapOpenAddressing *hashMap, int key) {
|
||||
// Find the bucket index for key
|
||||
int index = findBucket(hashMap, key);
|
||||
// If the key-value pair is found, return its val
|
||||
// If the pair is found, return its val
|
||||
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
|
||||
return hashMap->buckets[index]->val;
|
||||
}
|
||||
// Return an empty string if the key-value pair does not exist
|
||||
// If the pair is absent, return an empty string
|
||||
return "";
|
||||
}
|
||||
|
||||
/* Insert operation */
|
||||
/* Insert a key-value pair */
|
||||
void put(HashMapOpenAddressing *hashMap, int key, char *val) {
|
||||
// Grow the capacity when the load factor exceeds the threshold
|
||||
// Expand the table when the load factor exceeds the threshold
|
||||
if (loadFactor(hashMap) > hashMap->loadThres) {
|
||||
extend(hashMap);
|
||||
}
|
||||
// Find the bucket index for key
|
||||
int index = findBucket(hashMap, key);
|
||||
// If the key-value pair is found, overwrite val and return
|
||||
// If the pair is found, overwrite val and return
|
||||
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
|
||||
free(hashMap->buckets[index]->val);
|
||||
hashMap->buckets[index]->val = (char *)malloc(strlen(val) + 1);
|
||||
@@ -119,7 +119,7 @@ void put(HashMapOpenAddressing *hashMap, int key, char *val) {
|
||||
hashMap->buckets[index]->val[strlen(val)] = '\0';
|
||||
return;
|
||||
}
|
||||
// If the key-value pair is absent, insert it
|
||||
// If the pair is absent, insert it
|
||||
Pair *pair = (Pair *)malloc(sizeof(Pair));
|
||||
pair->key = key;
|
||||
pair->val = (char *)malloc(strlen(val) + 1);
|
||||
@@ -130,11 +130,11 @@ void put(HashMapOpenAddressing *hashMap, int key, char *val) {
|
||||
hashMap->size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
/* Remove a key-value pair */
|
||||
void removeItem(HashMapOpenAddressing *hashMap, int key) {
|
||||
// Find the bucket index for key
|
||||
int index = findBucket(hashMap, key);
|
||||
// If the key-value pair is found, replace it with a tombstone
|
||||
// If the pair is found, replace it with a deletion marker
|
||||
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
|
||||
Pair *pair = hashMap->buckets[index];
|
||||
free(pair->val);
|
||||
@@ -144,16 +144,16 @@ void removeItem(HashMapOpenAddressing *hashMap, int key) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Grow the hash table capacity */
|
||||
/* Expand the hash table */
|
||||
void extend(HashMapOpenAddressing *hashMap) {
|
||||
// Keep a reference to the original hash table
|
||||
// Save the original hash table
|
||||
Pair **bucketsTmp = hashMap->buckets;
|
||||
int oldCapacity = hashMap->capacity;
|
||||
// Initialize a new hash table with the expanded capacity
|
||||
// Initialize the larger hash table
|
||||
hashMap->capacity *= hashMap->extendRatio;
|
||||
hashMap->buckets = (Pair **)calloc(hashMap->capacity, sizeof(Pair *));
|
||||
hashMap->size = 0;
|
||||
// Move the key-value pairs from the original hash table to the new one
|
||||
// Move the key-value pairs from the old table into the new one
|
||||
for (int i = 0; i < oldCapacity; i++) {
|
||||
Pair *pair = bucketsTmp[i];
|
||||
if (pair != NULL && pair != hashMap->TOMBSTONE) {
|
||||
@@ -184,23 +184,23 @@ int main() {
|
||||
// Initialize the hash table
|
||||
HashMapOpenAddressing *hashmap = newHashMapOpenAddressing();
|
||||
|
||||
// Insert operation
|
||||
// Insert the key-value pair (key, val) into the hash table
|
||||
put(hashmap, 12836, "小哈");
|
||||
put(hashmap, 15937, "小啰");
|
||||
put(hashmap, 16750, "小算");
|
||||
put(hashmap, 13276, "小法");
|
||||
put(hashmap, 10583, "小鸭");
|
||||
// Insert a key-value pair
|
||||
// Insert the pair (key, val) into the hash table
|
||||
put(hashmap, 12836, "Xiao Ha");
|
||||
put(hashmap, 15937, "Xiao Luo");
|
||||
put(hashmap, 16750, "Xiao Suan");
|
||||
put(hashmap, 13276, "Xiao Fa");
|
||||
put(hashmap, 10583, "Xiao Ya");
|
||||
printf("\nHash table after insertion:\nKey -> Value\n");
|
||||
print(hashmap);
|
||||
|
||||
// Lookup operation
|
||||
// Look up key in the hash table to obtain val
|
||||
// Look up a value
|
||||
// Look up key in the hash table to get val
|
||||
char *name = get(hashmap, 13276);
|
||||
printf("\nLook up student ID 13276; name found: %s\n", name);
|
||||
printf("\nName for student ID 13276: %s\n", name);
|
||||
|
||||
// Remove operation
|
||||
// Remove the key-value pair (key, val) from the hash table
|
||||
// Remove a key-value pair
|
||||
// Remove the pair (key, val) from the hash table
|
||||
removeItem(hashmap, 16750);
|
||||
printf("\nHash table after removing 16750:\nKey -> Value\n");
|
||||
print(hashmap);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Additive hash */
|
||||
/* Additive hashing */
|
||||
int addHash(char *key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
@@ -16,7 +16,7 @@ int addHash(char *key) {
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* Multiplicative hash */
|
||||
/* Multiplicative hashing */
|
||||
int mulHash(char *key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
@@ -26,7 +26,7 @@ int mulHash(char *key) {
|
||||
return (int)hash;
|
||||
}
|
||||
|
||||
/* XOR hash */
|
||||
/* XOR hashing */
|
||||
int xorHash(char *key) {
|
||||
int hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
@@ -37,7 +37,7 @@ int xorHash(char *key) {
|
||||
return hash & MODULUS;
|
||||
}
|
||||
|
||||
/* Rotating hash */
|
||||
/* Rotation hashing */
|
||||
int rotHash(char *key) {
|
||||
long long hash = 0;
|
||||
const int MODULUS = 1000000007;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
#define MAX_SIZE 5000
|
||||
|
||||
/* Max heap */
|
||||
/* Max-heap */
|
||||
typedef struct {
|
||||
// size is the actual number of elements
|
||||
int size;
|
||||
@@ -16,19 +16,19 @@ typedef struct {
|
||||
int data[MAX_SIZE];
|
||||
} MaxHeap;
|
||||
|
||||
// Function declaration
|
||||
// Function declarations
|
||||
void siftDown(MaxHeap *maxHeap, int i);
|
||||
void siftUp(MaxHeap *maxHeap, int i);
|
||||
int parent(MaxHeap *maxHeap, int i);
|
||||
|
||||
/* Constructor: build a heap from the input array */
|
||||
/* Constructor: build a heap from a slice */
|
||||
MaxHeap *newMaxHeap(int nums[], int size) {
|
||||
// Place all elements in the heap
|
||||
// Push all elements onto the heap
|
||||
MaxHeap *maxHeap = (MaxHeap *)malloc(sizeof(MaxHeap));
|
||||
maxHeap->size = size;
|
||||
memcpy(maxHeap->data, nums, size * sizeof(int));
|
||||
for (int i = parent(maxHeap, size - 1); i >= 0; i--) {
|
||||
// Sift down from every non-leaf node
|
||||
// Heapify all non-leaf nodes
|
||||
siftDown(maxHeap, i);
|
||||
}
|
||||
return maxHeap;
|
||||
@@ -36,7 +36,7 @@ MaxHeap *newMaxHeap(int nums[], int size) {
|
||||
|
||||
/* Destructor */
|
||||
void delMaxHeap(MaxHeap *maxHeap) {
|
||||
// Free memory
|
||||
// Free the memory
|
||||
free(maxHeap);
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ int right(MaxHeap *maxHeap, int i) {
|
||||
|
||||
/* Get the parent index */
|
||||
int parent(MaxHeap *maxHeap, int i) {
|
||||
return (i - 1) / 2; // Integer division truncates toward zero
|
||||
return (i - 1) / 2; // Round down
|
||||
}
|
||||
|
||||
/* Swap elements */
|
||||
@@ -72,16 +72,16 @@ int isEmpty(MaxHeap *maxHeap) {
|
||||
return maxHeap->size == 0;
|
||||
}
|
||||
|
||||
/* Access the top element of the heap */
|
||||
/* Peek at the root */
|
||||
int peek(MaxHeap *maxHeap) {
|
||||
return maxHeap->data[0];
|
||||
}
|
||||
|
||||
/* Push an element onto the heap */
|
||||
void push(MaxHeap *maxHeap, int val) {
|
||||
// Normally, the number of nodes should remain below this limit
|
||||
// The default capacity should be enough for the expected number of nodes
|
||||
if (maxHeap->size == MAX_SIZE) {
|
||||
printf("Heap is full!");
|
||||
printf("heap is full!");
|
||||
return;
|
||||
}
|
||||
// Add a node
|
||||
@@ -96,25 +96,25 @@ void push(MaxHeap *maxHeap, int val) {
|
||||
int pop(MaxHeap *maxHeap) {
|
||||
// Handle an empty heap
|
||||
if (isEmpty(maxHeap)) {
|
||||
printf("Heap is empty!");
|
||||
printf("heap is empty!");
|
||||
return INT_MAX;
|
||||
}
|
||||
// Swap the root with the rightmost leaf on the last level (swap the first and last elements)
|
||||
// Swap the root and the rightmost leaf (the first and last elements)
|
||||
swap(maxHeap, 0, size(maxHeap) - 1);
|
||||
// Remove a node
|
||||
// Remove the node
|
||||
int val = maxHeap->data[maxHeap->size - 1];
|
||||
maxHeap->size--;
|
||||
// Sift down
|
||||
siftDown(maxHeap, 0);
|
||||
|
||||
// Return the top element of the heap
|
||||
// Return the root element
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Sift down starting from node i */
|
||||
/* Sift down from node i */
|
||||
void siftDown(MaxHeap *maxHeap, int i) {
|
||||
while (true) {
|
||||
// Find the node with the largest value among i, l, and r, and store its index in max
|
||||
// Store the index of the largest of nodes i, l, and r in max
|
||||
int l = left(maxHeap, i);
|
||||
int r = right(maxHeap, i);
|
||||
int max = i;
|
||||
@@ -124,7 +124,7 @@ void siftDown(MaxHeap *maxHeap, int i) {
|
||||
if (r < size(maxHeap) && maxHeap->data[r] > maxHeap->data[max]) {
|
||||
max = r;
|
||||
}
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
// Stop if i is already largest or both child indices l and r are out of bounds
|
||||
if (max == i) {
|
||||
break;
|
||||
}
|
||||
@@ -135,12 +135,12 @@ void siftDown(MaxHeap *maxHeap, int i) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Sift up starting from node i */
|
||||
/* Sift up from node i */
|
||||
void siftUp(MaxHeap *maxHeap, int i) {
|
||||
while (true) {
|
||||
// Get the parent of node i
|
||||
int p = parent(maxHeap, i);
|
||||
// Stop sifting when the root has been passed or the node needs no repair
|
||||
// Stop sifting at the root or when the node already satisfies the heap property
|
||||
if (p < 0 || maxHeap->data[i] <= maxHeap->data[p]) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -9,32 +9,32 @@
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize the heap */
|
||||
// Initialize a max heap
|
||||
// Initialize a max-heap
|
||||
int nums[] = {9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2};
|
||||
MaxHeap *maxHeap = newMaxHeap(nums, sizeof(nums) / sizeof(int));
|
||||
printf("After building a heap from the input array:\n");
|
||||
printf("Heap built from the input array:\n");
|
||||
printHeap(maxHeap->data, maxHeap->size);
|
||||
|
||||
/* Get the top element of the heap */
|
||||
printf("\nTop element of the heap: %d\n", peek(maxHeap));
|
||||
/* Get the root element */
|
||||
printf("\nRoot element: %d\n", peek(maxHeap));
|
||||
|
||||
/* Push an element onto the heap */
|
||||
push(maxHeap, 7);
|
||||
printf("\nAfter pushing element 7 onto the heap:\n");
|
||||
printf("\nHeap after pushing 7:\n");
|
||||
printHeap(maxHeap->data, maxHeap->size);
|
||||
|
||||
/* Pop the top element from the heap */
|
||||
/* Pop the root */
|
||||
int top = pop(maxHeap);
|
||||
printf("\nAfter popping top element %d from the heap:\n", top);
|
||||
printf("\nHeap after popping the root (%d):\n", top);
|
||||
printHeap(maxHeap->data, maxHeap->size);
|
||||
|
||||
/* Get the heap size */
|
||||
printf("\nNumber of elements in the heap: %d\n", size(maxHeap));
|
||||
|
||||
/* Check whether the heap is empty */
|
||||
printf("\nIs the heap empty: %d\n", isEmpty(maxHeap));
|
||||
printf("\nIs the heap empty? %d\n", isEmpty(maxHeap));
|
||||
|
||||
// Free memory
|
||||
// Free the memory
|
||||
delMaxHeap(maxHeap);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,25 +8,25 @@
|
||||
|
||||
/* Push an element onto the heap */
|
||||
void pushMinHeap(MaxHeap *maxHeap, int val) {
|
||||
// Negate the element
|
||||
// Negate the elements
|
||||
push(maxHeap, -val);
|
||||
}
|
||||
|
||||
/* Pop an element from the heap */
|
||||
int popMinHeap(MaxHeap *maxHeap) {
|
||||
// Negate the element
|
||||
// Negate the elements
|
||||
return -pop(maxHeap);
|
||||
}
|
||||
|
||||
/* Access the top element of the heap */
|
||||
/* Peek at the root */
|
||||
int peekMinHeap(MaxHeap *maxHeap) {
|
||||
// Negate the element
|
||||
// Negate the elements
|
||||
return -peek(maxHeap);
|
||||
}
|
||||
|
||||
/* Get the elements in the heap */
|
||||
/* Retrieve the elements in the heap */
|
||||
int *getMinHeap(MaxHeap *maxHeap) {
|
||||
// Negate every element in the heap and store the results in array res
|
||||
// Negate each heap element and store it in the res array
|
||||
int *res = (int *)malloc(maxHeap->size * sizeof(int));
|
||||
for (int i = 0; i < maxHeap->size; i++) {
|
||||
res[i] = -maxHeap->data[i];
|
||||
@@ -34,10 +34,10 @@ int *getMinHeap(MaxHeap *maxHeap) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Use a heap to find the k largest elements in an array */
|
||||
/* Find the k largest elements in an array using a heap */
|
||||
int *topKHeap(int *nums, int sizeNums, int k) {
|
||||
// Initialize a min heap
|
||||
// Note: negate every element to simulate a min heap with a max heap
|
||||
// Initialize a min-heap
|
||||
// Negate all values so the max-heap acts as a min-heap
|
||||
int *empty = (int *)malloc(0);
|
||||
MaxHeap *maxHeap = newMaxHeap(empty, 0);
|
||||
// Push the first k array elements onto the heap
|
||||
@@ -46,14 +46,14 @@ int *topKHeap(int *nums, int sizeNums, int k) {
|
||||
}
|
||||
// Starting with element k+1, keep the heap size at k
|
||||
for (int i = k; i < sizeNums; i++) {
|
||||
// If the current element is larger than the heap top, pop the top element and push the current element
|
||||
// If the current element exceeds the root, pop the root and push the current element
|
||||
if (nums[i] > peekMinHeap(maxHeap)) {
|
||||
popMinHeap(maxHeap);
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
}
|
||||
int *res = getMinHeap(maxHeap);
|
||||
// Free memory
|
||||
// Free the memory
|
||||
delMaxHeap(maxHeap);
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -6,39 +6,39 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Binary search (closed interval) */
|
||||
/* Binary search on a closed interval */
|
||||
int binarySearch(int *nums, int len, int target) {
|
||||
// Initialize the closed interval [0, n-1], with i and j pointing to the first and last elements
|
||||
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
|
||||
int i = 0, j = len - 1;
|
||||
// Loop until the search interval is empty (when i > j)
|
||||
// Stop when the search interval is empty (i > j)
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums[m] < target) // In this case, target must be in [m+1, j] if it exists
|
||||
int m = i + (j - i) / 2; // Compute the midpoint index m
|
||||
if (nums[m] < target) // Any match must lie in [m+1, j]
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // In this case, target must be in [i, m-1] if it exists
|
||||
else if (nums[m] > target) // Any match must lie in [i, m-1]
|
||||
j = m - 1;
|
||||
else // The target element was found; return its index
|
||||
else // Found the target. Return its index
|
||||
return m;
|
||||
}
|
||||
// The target element was not found; return -1
|
||||
// Target not found. Return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Binary search (left-closed, right-open interval) */
|
||||
/* Binary search on a left-closed, right-open interval */
|
||||
int binarySearchLCRO(int *nums, int len, int target) {
|
||||
// Initialize the left-closed, right-open interval [0, n), with i at the first element and j one past the last
|
||||
// Initialize [0, n) with i at the first element and j one past the last
|
||||
int i = 0, j = len;
|
||||
// Loop until the search interval is empty (when i = j)
|
||||
// Stop when the search interval is empty (i = j)
|
||||
while (i < j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums[m] < target) // In this case, target must be in [m+1, j) if it exists
|
||||
int m = i + (j - i) / 2; // Compute the midpoint index m
|
||||
if (nums[m] < target) // Any match must lie in [m+1, j)
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // In this case, target must be in [i, m) if it exists
|
||||
else if (nums[m] > target) // Any match must lie in [i, m)
|
||||
j = m;
|
||||
else // The target element was found; return its index
|
||||
else // Found the target. Return its index
|
||||
return m;
|
||||
}
|
||||
// The target element was not found; return -1
|
||||
// Target not found. Return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -47,13 +47,13 @@ int main() {
|
||||
int target = 6;
|
||||
int nums[10] = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
|
||||
|
||||
/* Binary search (closed interval) */
|
||||
/* Binary search on a closed interval */
|
||||
int index = binarySearch(nums, 10, target);
|
||||
printf("Index of target element 6 = %d\n", index);
|
||||
printf("Index of target 6 = %d\n", index);
|
||||
|
||||
/* Binary search (left-closed, right-open interval) */
|
||||
/* Binary search on a left-closed, right-open interval */
|
||||
index = binarySearchLCRO(nums, 10, target);
|
||||
printf("Index of target element 6 = %d\n", index);
|
||||
printf("Index of target 6 = %d\n", index);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,50 +6,50 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Find an insertion point using binary search (with duplicates) */
|
||||
/* Binary search for an insertion point (duplicates allowed) */
|
||||
int binarySearchInsertion(int *nums, int numSize, int target) {
|
||||
int i = 0, j = numSize - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
int m = i + (j - i) / 2; // Compute the midpoint index m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
i = m + 1; // Any match must lie in [m+1, j]
|
||||
} else {
|
||||
j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
|
||||
j = m - 1; // Look in [i, m-1] for the rightmost element less than target
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Find the leftmost occurrence of target using binary search */
|
||||
/* Use binary search to find the leftmost occurrence of target */
|
||||
int binarySearchLeftEdge(int *nums, int numSize, int target) {
|
||||
// This is equivalent to finding the insertion point of target
|
||||
// Equivalent to finding the insertion point for target
|
||||
int i = binarySearchInsertion(nums, numSize, target);
|
||||
// If target was not found, return -1
|
||||
// Target not found. Return -1
|
||||
if (i == numSize || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Target was found; return index i
|
||||
// Found target. Return index i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Find the rightmost occurrence of target using binary search */
|
||||
/* Use binary search to find the rightmost occurrence of target */
|
||||
int binarySearchRightEdge(int *nums, int numSize, int target) {
|
||||
// Reduce the problem to finding the leftmost insertion point of target + 1
|
||||
// Search for the leftmost occurrence of target + 1
|
||||
int i = binarySearchInsertion(nums, numSize, target + 1);
|
||||
// j points to the rightmost target, while i points to the first element greater than target
|
||||
// j points to the rightmost occurrence of target, and i to the first larger element
|
||||
int j = i - 1;
|
||||
// If target was not found, return -1
|
||||
// Target not found. Return -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Target was found; return index j
|
||||
// Found target. Return index j
|
||||
return j;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Array containing duplicate elements
|
||||
// Array with duplicates
|
||||
int nums[] = {1, 3, 6, 6, 6, 6, 6, 10, 12, 15};
|
||||
printf("\nArray nums = ");
|
||||
printArray(nums, sizeof(nums) / sizeof(nums[0]));
|
||||
@@ -58,9 +58,9 @@ int main() {
|
||||
int targets[] = {6, 7};
|
||||
for (int i = 0; i < sizeof(targets) / sizeof(targets[0]); i++) {
|
||||
int index = binarySearchLeftEdge(nums, sizeof(nums) / sizeof(nums[0]), targets[i]);
|
||||
printf("Index of the leftmost occurrence of %d: %d\n", targets[i], index);
|
||||
printf("Index of the leftmost occurrence of %d = %d\n", targets[i], index);
|
||||
index = binarySearchRightEdge(nums, sizeof(nums) / sizeof(nums[0]), targets[i]);
|
||||
printf("Index of the rightmost occurrence of %d: %d\n", targets[i], index);
|
||||
printf("Index of the rightmost occurrence of %d = %d\n", targets[i], index);
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,34 +6,34 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Find an insertion point using binary search (no duplicates) */
|
||||
/* Binary search for an insertion point (no duplicates) */
|
||||
int binarySearchInsertionSimple(int *nums, int numSize, int target) {
|
||||
int i = 0, j = numSize - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
int m = i + (j - i) / 2; // Compute the midpoint index m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
i = m + 1; // Any match must lie in [m+1, j]
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // Target must be in [i, m-1] if it exists
|
||||
j = m - 1; // Any match must lie in [i, m-1]
|
||||
} else {
|
||||
return m; // Target was found; return insertion point m
|
||||
return m; // Found target. Return insertion point m
|
||||
}
|
||||
}
|
||||
// Target was not found; return insertion point i
|
||||
// Target not found. Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Find an insertion point using binary search (with duplicates) */
|
||||
/* Binary search for an insertion point (duplicates allowed) */
|
||||
int binarySearchInsertion(int *nums, int numSize, int target) {
|
||||
int i = 0, j = numSize - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
int m = i + (j - i) / 2; // Compute the midpoint index m
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
i = m + 1; // Any match must lie in [m+1, j]
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // Target must be in [i, m-1] if it exists
|
||||
j = m - 1; // Any match must lie in [i, m-1]
|
||||
} else {
|
||||
j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
|
||||
j = m - 1; // Look in [i, m-1] for the rightmost element less than target
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
@@ -42,26 +42,26 @@ int binarySearchInsertion(int *nums, int numSize, int target) {
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// Array with no duplicate elements
|
||||
// Array without duplicates
|
||||
int nums1[] = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
|
||||
printf("\nArray nums = ");
|
||||
printArray(nums1, sizeof(nums1) / sizeof(nums1[0]));
|
||||
// Find an insertion point using binary search
|
||||
// Find the insertion point using binary search
|
||||
int targets1[] = {6, 9};
|
||||
for (int i = 0; i < sizeof(targets1) / sizeof(targets1[0]); i++) {
|
||||
int index = binarySearchInsertionSimple(nums1, sizeof(nums1) / sizeof(nums1[0]), targets1[i]);
|
||||
printf("Insertion index for element %d: %d\n", targets1[i], index);
|
||||
printf("Insertion index for %d = %d\n", targets1[i], index);
|
||||
}
|
||||
|
||||
// Array containing duplicate elements
|
||||
// Array with duplicates
|
||||
int nums2[] = {1, 3, 6, 6, 6, 6, 6, 10, 12, 15};
|
||||
printf("\nArray nums = ");
|
||||
printArray(nums2, sizeof(nums2) / sizeof(nums2[0]));
|
||||
// Find an insertion point using binary search
|
||||
// Find the insertion point using binary search
|
||||
int targets2[] = {2, 6, 20};
|
||||
for (int i = 0; i < sizeof(targets2) / sizeof(int); i++) {
|
||||
int index = binarySearchInsertion(nums2, sizeof(nums2) / sizeof(nums2[0]), targets2[i]);
|
||||
printf("Insertion index for element %d: %d\n", targets2[i], index);
|
||||
printf("Insertion index for %d = %d\n", targets2[i], index);
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Method 1: brute-force enumeration */
|
||||
/* Method 1: Brute-force enumeration */
|
||||
int *twoSumBruteForce(int *nums, int numsSize, int target, int *returnSize) {
|
||||
for (int i = 0; i < numsSize; ++i) {
|
||||
for (int j = i + 1; j < numsSize; ++j) {
|
||||
@@ -29,14 +29,14 @@ typedef struct {
|
||||
UT_hash_handle hh; // Implemented using uthash.h
|
||||
} HashTable;
|
||||
|
||||
/* Look up a key in the hash table */
|
||||
/* Look up a hash table entry */
|
||||
HashTable *find(HashTable *h, int key) {
|
||||
HashTable *tmp;
|
||||
HASH_FIND_INT(h, &key, tmp);
|
||||
return tmp;
|
||||
}
|
||||
|
||||
/* Insert an entry into the hash table */
|
||||
/* Insert a hash table entry */
|
||||
void insert(HashTable **h, int key, int val) {
|
||||
HashTable *t = find(*h, key);
|
||||
if (t == NULL) {
|
||||
@@ -48,7 +48,7 @@ void insert(HashTable **h, int key, int val) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Method 2: auxiliary hash table */
|
||||
/* Method 2: Auxiliary hash table */
|
||||
int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
|
||||
HashTable *hashtable = NULL;
|
||||
for (int i = 0; i < numsSize; i++) {
|
||||
@@ -67,10 +67,10 @@ int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
// ======= Test case =======
|
||||
// ======= Test Case =======
|
||||
int nums[] = {2, 7, 11, 15};
|
||||
int target = 13;
|
||||
// ====== Driver code ======
|
||||
// ====== Driver Code ======
|
||||
int returnSize;
|
||||
int *res = twoSumBruteForce(nums, sizeof(nums) / sizeof(int), target, &returnSize);
|
||||
// Method 1
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
void bubbleSort(int nums[], int size) {
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (int i = size - 1; i > 0; i--) {
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
// Inner loop: swap the largest element in [0, i] to the right end of the range
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
int temp = nums[j];
|
||||
@@ -21,12 +21,12 @@ void bubbleSort(int nums[], int size) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Bubble sort (flag optimization)*/
|
||||
/* Bubble sort with an early-exit flag*/
|
||||
void bubbleSortWithFlag(int nums[], int size) {
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (int i = size - 1; i > 0; i--) {
|
||||
bool flag = false;
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
// Inner loop: swap the largest element in [0, i] to the right end of the range
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
int temp = nums[j];
|
||||
@@ -40,7 +40,7 @@ void bubbleSortWithFlag(int nums[], int size) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int nums[6] = {4, 1, 3, 1, 5, 2};
|
||||
printf("After bubble sort: ");
|
||||
|
||||
@@ -18,7 +18,7 @@ int compare(const void *a, const void *b) {
|
||||
/* Bucket sort */
|
||||
void bucketSort(float nums[], int n) {
|
||||
int k = n / 2; // Initialize k = n/2 buckets
|
||||
int *sizes = malloc(k * sizeof(int)); // Record the size of each bucket
|
||||
int *sizes = malloc(k * sizeof(int)); // Track the size of each bucket
|
||||
float **buckets = malloc(k * sizeof(float *)); // Array of dynamic arrays (buckets)
|
||||
// Preallocate enough space for each bucket
|
||||
for (int i = 0; i < k; ++i) {
|
||||
@@ -34,7 +34,7 @@ void bucketSort(float nums[], int n) {
|
||||
for (int i = 0; i < k; ++i) {
|
||||
qsort(buckets[i], sizes[i], sizeof(float), compare);
|
||||
}
|
||||
// 3. Merge the sorted buckets
|
||||
// 3. Combine the sorted buckets
|
||||
int idx = 0;
|
||||
for (int i = 0; i < k; ++i) {
|
||||
for (int j = 0; j < sizes[i]; ++j) {
|
||||
@@ -45,9 +45,9 @@ void bucketSort(float nums[], int n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
// Assume the input consists of floating-point numbers in [0, 1)
|
||||
// Assume floating-point inputs in [0, 1)
|
||||
float nums[SIZE] = {0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f};
|
||||
bucketSort(nums, SIZE);
|
||||
printf("After bucket sort, nums = ");
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation; cannot be used to sort objects
|
||||
// Simple implementation that cannot sort objects
|
||||
void countingSortNaive(int nums[], int size) {
|
||||
// 1. Find the maximum array element m
|
||||
// 1. Find the largest array element m
|
||||
int m = 0;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (nums[i] > m) {
|
||||
@@ -17,12 +17,12 @@ void countingSortNaive(int nums[], int size) {
|
||||
}
|
||||
}
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
// counter[num] holds the number of occurrences of num
|
||||
int *counter = calloc(m + 1, sizeof(int));
|
||||
for (int i = 0; i < size; i++) {
|
||||
counter[nums[i]]++;
|
||||
}
|
||||
// 3. Traverse counter and fill the original array nums with the elements
|
||||
// 3. Traverse counter and write each value back into nums
|
||||
int i = 0;
|
||||
for (int num = 0; num < m + 1; num++) {
|
||||
for (int j = 0; j < counter[num]; j++, i++) {
|
||||
@@ -34,9 +34,9 @@ void countingSortNaive(int nums[], int size) {
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Full, stable implementation; can be adapted to sort objects
|
||||
// Full implementation that can sort objects and is stable
|
||||
void countingSort(int nums[], int size) {
|
||||
// 1. Find the maximum array element m
|
||||
// 1. Find the largest array element m
|
||||
int m = 0;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (nums[i] > m) {
|
||||
@@ -44,37 +44,37 @@ void countingSort(int nums[], int size) {
|
||||
}
|
||||
}
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
// counter[num] holds the number of occurrences of num
|
||||
int *counter = calloc(m + 1, sizeof(int));
|
||||
for (int i = 0; i < size; i++) {
|
||||
counter[nums[i]]++;
|
||||
}
|
||||
// 3. Compute prefix sums of counter to convert occurrence counts into end positions
|
||||
// That is, counter[num]-1 is the index of the last occurrence of num in res
|
||||
// 3. Compute prefix sums in counter to locate the last position for each value
|
||||
// That is, counter[num]-1 is the last index of num in res
|
||||
for (int i = 0; i < m; i++) {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. Traverse nums in reverse and place each element in the result array res
|
||||
// Initialize array res to store the result
|
||||
// 4. Traverse nums backward and place each element in the result array res
|
||||
// Initialize the result array res
|
||||
int *res = malloc(sizeof(int) * size);
|
||||
for (int i = size - 1; i >= 0; i--) {
|
||||
int num = nums[i];
|
||||
res[counter[num] - 1] = num; // Place num at the corresponding index
|
||||
counter[num]--; // Decrement the prefix sum by 1 to determine where to place the next occurrence of num
|
||||
res[counter[num] - 1] = num; // Place num at its corresponding index
|
||||
counter[num]--; // Decrement the prefix sum by 1 to find the next index for num
|
||||
}
|
||||
// Overwrite the original array nums with the result array res
|
||||
// Copy res back into the original array nums
|
||||
memcpy(nums, res, size * sizeof(int));
|
||||
// 5. Free memory
|
||||
free(res);
|
||||
free(counter);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int nums[] = {1, 0, 1, 2, 0, 4, 0, 2, 2, 4};
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
countingSortNaive(nums, size);
|
||||
printf("After counting sort (without support for objects), nums = ");
|
||||
printf("After counting sort (values only), nums = ");
|
||||
printArray(nums, size);
|
||||
|
||||
int nums1[] = {1, 0, 1, 2, 0, 4, 0, 2, 2, 4};
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/* Sift down from node i in a heap of size n */
|
||||
void siftDown(int nums[], int n, int i) {
|
||||
while (1) {
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
// Let ma be the index of the largest of nodes i, l, and r
|
||||
int l = 2 * i + 1;
|
||||
int r = 2 * i + 2;
|
||||
int ma = i;
|
||||
@@ -17,7 +17,7 @@ void siftDown(int nums[], int n, int i) {
|
||||
ma = l;
|
||||
if (r < n && nums[r] > nums[ma])
|
||||
ma = r;
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
// Stop if i is the largest or both child indices l and r are out of bounds
|
||||
if (ma == i) {
|
||||
break;
|
||||
}
|
||||
@@ -32,22 +32,22 @@ void siftDown(int nums[], int n, int i) {
|
||||
|
||||
/* Heap sort */
|
||||
void heapSort(int nums[], int n) {
|
||||
// Build the heap by sifting down from every non-leaf node
|
||||
// Build the heap by sifting down from each non-leaf node
|
||||
for (int i = n / 2 - 1; i >= 0; --i) {
|
||||
siftDown(nums, n, i);
|
||||
}
|
||||
// Extract the largest element from the heap, repeating for n-1 rounds
|
||||
// Extract the maximum from the heap in each of n-1 rounds
|
||||
for (int i = n - 1; i > 0; --i) {
|
||||
// Swap the root with the rightmost leaf on the last level (the first and last elements of the current heap)
|
||||
// Swap the root and rightmost leaf (the first and last elements)
|
||||
int tmp = nums[0];
|
||||
nums[0] = nums[i];
|
||||
nums[i] = tmp;
|
||||
// Sift down starting at the root
|
||||
// Sift down from the root
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int nums[] = {4, 1, 3, 1, 5, 2};
|
||||
int n = sizeof(nums) / sizeof(nums[0]);
|
||||
|
||||
@@ -22,7 +22,7 @@ void insertionSort(int nums[], int size) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int nums[] = {4, 1, 3, 1, 5, 2};
|
||||
insertionSort(nums, 6);
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
|
||||
/* Merge the left and right subarrays */
|
||||
void merge(int *nums, int left, int mid, int right) {
|
||||
// The left subarray spans [left, mid], and the right subarray spans [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged result
|
||||
// The left subarray spans [left, mid] and the right spans [mid+1, right]
|
||||
// Create a temporary array tmp for the merged result
|
||||
int tmpSize = right - left + 1;
|
||||
int *tmp = (int *)malloc(tmpSize * sizeof(int));
|
||||
// Initialize the starting indices of the left and right subarrays
|
||||
int i = left, j = mid + 1, k = 0;
|
||||
// While both subarrays have elements remaining, compare them and copy the smaller element into the temporary array
|
||||
// While both subarrays have elements left, compare their front elements and copy the smaller one to the temporary array
|
||||
while (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j]) {
|
||||
tmp[k++] = nums[i++];
|
||||
@@ -22,14 +22,14 @@ void merge(int *nums, int left, int mid, int right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
}
|
||||
// Copy the remaining elements of the left and right subarrays into the temporary array
|
||||
// Copy any remaining elements from either subarray to the temporary array
|
||||
while (i <= mid) {
|
||||
tmp[k++] = nums[i++];
|
||||
}
|
||||
while (j <= right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// Copy the elements of temporary array tmp back into the corresponding range of the original array nums
|
||||
// Copy tmp back into the corresponding range of nums
|
||||
for (k = 0; k < tmpSize; ++k) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
@@ -41,16 +41,16 @@ void merge(int *nums, int left, int mid, int right) {
|
||||
void mergeSort(int *nums, int left, int right) {
|
||||
// Base case
|
||||
if (left >= right)
|
||||
return; // Stop recursing when the subarray has at most one element
|
||||
// Divide phase
|
||||
int mid = left + (right - left) / 2; // Calculate the midpoint
|
||||
return; // Stop recursing when the subarray has length 1
|
||||
// Divide
|
||||
int mid = left + (right - left) / 2; // Find the midpoint
|
||||
mergeSort(nums, left, mid); // Recurse on the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recurse on the right subarray
|
||||
// Merge phase
|
||||
// Merge
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Merge sort */
|
||||
int nums[] = {7, 3, 2, 6, 0, 1, 5, 4};
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Swap the elements */
|
||||
/* Swap elements */
|
||||
void swap(int nums[], int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Two-pointer partitioning */
|
||||
/* Partition with two pointers */
|
||||
int partition(int nums[], int left, int right) {
|
||||
// Use nums[left] as the pivot
|
||||
int i = left, j = right;
|
||||
@@ -27,28 +27,28 @@ int partition(int nums[], int left, int right) {
|
||||
// Swap these two elements
|
||||
swap(nums, i, j);
|
||||
}
|
||||
// Swap the pivot into the boundary position between the two subarrays
|
||||
// Swap the pivot into place between the two subarrays
|
||||
swap(nums, i, left);
|
||||
// Return the pivot index
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
/* Quicksort */
|
||||
void quickSort(int nums[], int left, int right) {
|
||||
// Stop recursing when the subarray has at most one element
|
||||
// Stop recursing when the subarray has length 1
|
||||
if (left >= right) {
|
||||
return;
|
||||
}
|
||||
// Two-pointer partitioning
|
||||
// Partition with two pointers
|
||||
int pivot = partition(nums, left, right);
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
|
||||
// Quick sort with median-of-three pivot optimization follows
|
||||
// Quicksort with median-of-three pivot selection follows
|
||||
|
||||
/* Select the median of three candidate elements */
|
||||
/* Select the median of three candidates */
|
||||
int medianThree(int nums[], int left, int mid, int right) {
|
||||
int l = nums[left], m = nums[mid], r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
@@ -58,11 +58,11 @@ int medianThree(int nums[], int left, int mid, int right) {
|
||||
return right;
|
||||
}
|
||||
|
||||
/* Two-pointer partitioning (median of three) */
|
||||
/* Partition with two pointers (median of three) */
|
||||
int partitionMedian(int nums[], int left, int right) {
|
||||
// Select the median of three candidate elements
|
||||
// Select the median of three candidates
|
||||
int med = medianThree(nums, left, (left + right) / 2, right);
|
||||
// Swap the median into the leftmost position of the array
|
||||
// Swap the median into the leftmost position
|
||||
swap(nums, left, med);
|
||||
// Use nums[left] as the pivot
|
||||
int i = left, j = right;
|
||||
@@ -73,31 +73,31 @@ int partitionMedian(int nums[], int left, int right) {
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
swap(nums, i, left); // Swap the pivot into place between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort (median of three) */
|
||||
/* Quicksort (median of three) */
|
||||
void quickSortMedian(int nums[], int left, int right) {
|
||||
// Stop recursing when the subarray has at most one element
|
||||
// Stop recursing when the subarray has length 1
|
||||
if (left >= right)
|
||||
return;
|
||||
// Two-pointer partitioning
|
||||
// Partition with two pointers
|
||||
int pivot = partitionMedian(nums, left, right);
|
||||
// Recurse on the left and right subarrays
|
||||
quickSortMedian(nums, left, pivot - 1);
|
||||
quickSortMedian(nums, pivot + 1, right);
|
||||
}
|
||||
|
||||
// Quick sort with recursion depth optimization follows
|
||||
// Quicksort with reduced recursion depth follows
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
/* Quicksort with reduced recursion depth */
|
||||
void quickSortTailCall(int nums[], int left, int right) {
|
||||
// Stop when the subarray has at most one element
|
||||
// Stop when the subarray has length 1
|
||||
while (left < right) {
|
||||
// Perform two-pointer partitioning
|
||||
// Partition with two pointers
|
||||
int pivot = partition(nums, left, right);
|
||||
// Apply quick sort to the shorter of the two subarrays
|
||||
// Apply quicksort to the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
// Recursively sort the left subarray
|
||||
quickSortTailCall(nums, left, pivot - 1);
|
||||
@@ -112,25 +112,25 @@ void quickSortTailCall(int nums[], int left, int right) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* Quick sort */
|
||||
/* Quicksort */
|
||||
int nums[] = {2, 4, 1, 0, 3, 5};
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
quickSort(nums, 0, size - 1);
|
||||
printf("After quick sort, nums = ");
|
||||
printf("After quicksort, nums = ");
|
||||
printArray(nums, size);
|
||||
|
||||
/* Quick sort (median pivot optimization) */
|
||||
/* Quicksort with median-of-three pivot selection */
|
||||
int nums1[] = {2, 4, 1, 0, 3, 5};
|
||||
quickSortMedian(nums1, 0, size - 1);
|
||||
printf("After quick sort (median pivot optimization), nums = ");
|
||||
printf("After median-of-three quicksort, nums = ");
|
||||
printArray(nums1, size);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
/* Quicksort with reduced recursion depth */
|
||||
int nums2[] = {2, 4, 1, 0, 3, 5};
|
||||
quickSortTailCall(nums2, 0, size - 1);
|
||||
printf("After quick sort (recursion depth optimization), nums = ");
|
||||
printf("After quicksort with reduced recursion depth, nums = ");
|
||||
printArray(nums1, size);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,37 +6,37 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Get the k-th digit of num, where exp = 10^(k-1) */
|
||||
/* Get digit k of num, where exp = 10^(k-1) */
|
||||
int digit(int num, int exp) {
|
||||
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
|
||||
// Passing exp instead of k avoids repeating the costly exponentiation here
|
||||
return (num / exp) % 10;
|
||||
}
|
||||
|
||||
/* Counting sort (sort nums by the k-th digit) */
|
||||
/* Counting sort by digit k of each element in nums */
|
||||
void countingSortDigit(int nums[], int size, int exp) {
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs length 10
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs 10 entries
|
||||
int *counter = (int *)malloc((sizeof(int) * 10));
|
||||
memset(counter, 0, sizeof(int) * 10); // Initialize the counts to 0
|
||||
// Count the occurrences of each digit from 0 to 9
|
||||
memset(counter, 0, sizeof(int) * 10); // Initialize to 0 so the memory can be freed later
|
||||
// Count the occurrences of digits 0 through 9
|
||||
for (int i = 0; i < size; i++) {
|
||||
// Get the k-th digit of nums[i] and store it in d
|
||||
// Let d be digit k of nums[i]
|
||||
int d = digit(nums[i], exp);
|
||||
// Count the occurrences of digit d
|
||||
// Count this occurrence of digit d
|
||||
counter[d]++;
|
||||
}
|
||||
// Compute prefix sums to convert occurrence counts into array positions
|
||||
// Compute prefix sums to convert counts into array positions
|
||||
for (int i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse and place each element into res according to the bucket counts
|
||||
// Traverse backward and use the bucket counts to place each element in res
|
||||
int *res = (int *)malloc(sizeof(int) * size);
|
||||
for (int i = size - 1; i >= 0; i--) {
|
||||
int d = digit(nums[i], exp);
|
||||
int j = counter[d] - 1; // Get the destination index j for digit d in the array
|
||||
int j = counter[d] - 1; // Get the array index j for d
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d]--; // Decrease the count for d by 1
|
||||
counter[d]--; // Decrement the count for d by 1
|
||||
}
|
||||
// Overwrite the original array nums with the result
|
||||
// Copy the result back into nums
|
||||
for (int i = 0; i < size; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
@@ -47,23 +47,23 @@ void countingSortDigit(int nums[], int size, int exp) {
|
||||
|
||||
/* Radix sort */
|
||||
void radixSort(int nums[], int size) {
|
||||
// Get the largest array element to determine the maximum number of digits
|
||||
// Find the largest element to determine the maximum number of digits
|
||||
int max = INT32_MIN;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (nums[i] > max) {
|
||||
max = nums[i];
|
||||
}
|
||||
}
|
||||
// Process digits from least significant to most significant
|
||||
// Work from the least significant digit to the most significant
|
||||
for (int exp = 1; max >= exp; exp *= 10)
|
||||
// Apply counting sort to the k-th digit of the array elements
|
||||
// Apply counting sort to the array elements by digit k
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// That is, exp = 10^(k-1)
|
||||
// Here exp = 10^(k-1)
|
||||
countingSortDigit(nums, size, exp);
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
// Radix sort
|
||||
int nums[] = {10546151, 35663510, 42865989, 34862445, 81883077,
|
||||
|
||||
@@ -23,7 +23,7 @@ void selectionSort(int nums[], int n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int nums[] = {4, 1, 3, 1, 5, 2};
|
||||
int n = sizeof(nums) / sizeof(nums[0]);
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Deque implemented with a circular array */
|
||||
/* Deque backed by a circular array */
|
||||
typedef struct {
|
||||
int *nums; // Array that stores the queue elements
|
||||
int front; // Front pointer, pointing to the first element
|
||||
int queSize; // Current number of elements in the deque
|
||||
int queCapacity; // Queue capacity
|
||||
int *nums; // Array that stores the deque elements
|
||||
int front; // Index of the front element
|
||||
int queSize; // Number of elements in the deque
|
||||
int queCapacity; // Deque capacity
|
||||
} ArrayDeque;
|
||||
|
||||
/* Constructor */
|
||||
@@ -45,66 +45,66 @@ bool empty(ArrayDeque *deque) {
|
||||
return deque->queSize == 0;
|
||||
}
|
||||
|
||||
/* Calculate an index in the circular array */
|
||||
/* Compute the circular array index */
|
||||
int dequeIndex(ArrayDeque *deque, int i) {
|
||||
// Use modulo to connect the end of the array to its beginning
|
||||
// When i passes the end of the array, wrap to the beginning
|
||||
// When i passes the beginning of the array, wrap around to the end
|
||||
// Use the remainder to wrap indices around the array
|
||||
// When i goes past the end, wrap it back to the start
|
||||
// When i goes before the start, wrap it around to the end
|
||||
return ((i + capacity(deque)) % capacity(deque));
|
||||
}
|
||||
|
||||
/* Enqueue at the front */
|
||||
/* Add an element at the front */
|
||||
void pushFirst(ArrayDeque *deque, int num) {
|
||||
if (deque->queSize == capacity(deque)) {
|
||||
printf("Deque is full\r\n");
|
||||
return;
|
||||
}
|
||||
// Move the front pointer one position to the left
|
||||
// Use modulo to wrap front to the end when it passes the beginning
|
||||
// Move the front index one slot to the left
|
||||
// Use the remainder to wrap front to the end if it goes before the start
|
||||
deque->front = dequeIndex(deque, deque->front - 1);
|
||||
// Add num to the front
|
||||
// Add num at the front
|
||||
deque->nums[deque->front] = num;
|
||||
deque->queSize++;
|
||||
}
|
||||
|
||||
/* Enqueue at the rear */
|
||||
/* Add an element at the rear */
|
||||
void pushLast(ArrayDeque *deque, int num) {
|
||||
if (deque->queSize == capacity(deque)) {
|
||||
printf("Deque is full\r\n");
|
||||
return;
|
||||
}
|
||||
// Calculate the rear pointer, which points one position past the last element
|
||||
// Compute the index one slot past the rear element
|
||||
int rear = dequeIndex(deque, deque->front + deque->queSize);
|
||||
// Add num to the rear
|
||||
// Add num at the rear
|
||||
deque->nums[rear] = num;
|
||||
deque->queSize++;
|
||||
}
|
||||
|
||||
/* Access the front element */
|
||||
/* Peek at the front element */
|
||||
int peekFirst(ArrayDeque *deque) {
|
||||
// Access error: the deque is empty
|
||||
// Cannot access an element in an empty deque
|
||||
assert(empty(deque) == 0);
|
||||
return deque->nums[deque->front];
|
||||
}
|
||||
|
||||
/* Access the rear element */
|
||||
/* Peek at the rear element */
|
||||
int peekLast(ArrayDeque *deque) {
|
||||
// Access error: the deque is empty
|
||||
// Cannot access an element in an empty deque
|
||||
assert(empty(deque) == 0);
|
||||
int last = dequeIndex(deque, deque->front + deque->queSize - 1);
|
||||
return deque->nums[last];
|
||||
}
|
||||
|
||||
/* Dequeue from the front */
|
||||
/* Remove and return the front element */
|
||||
int popFirst(ArrayDeque *deque) {
|
||||
int num = peekFirst(deque);
|
||||
// Advance the front pointer by one position
|
||||
// Advance the front index by one
|
||||
deque->front = dequeIndex(deque, deque->front + 1);
|
||||
deque->queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Dequeue from the rear */
|
||||
/* Remove and return the rear element */
|
||||
int popLast(ArrayDeque *deque) {
|
||||
int num = peekLast(deque);
|
||||
deque->queSize--;
|
||||
@@ -125,47 +125,47 @@ int *toArray(ArrayDeque *deque, int *queSize) {
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
/* Initialize the queue */
|
||||
/* Initialize the deque */
|
||||
int capacity = 10;
|
||||
int queSize;
|
||||
ArrayDeque *deque = newArrayDeque(capacity);
|
||||
pushLast(deque, 3);
|
||||
pushLast(deque, 2);
|
||||
pushLast(deque, 5);
|
||||
printf("Deque deque = ");
|
||||
printf("deque = ");
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
|
||||
/* Access an element */
|
||||
/* Peek at the front and rear elements */
|
||||
int peekFirstNum = peekFirst(deque);
|
||||
printf("Front element peekFirst = %d\r\n", peekFirstNum);
|
||||
printf("Front element (peekFirst) = %d\r\n", peekFirstNum);
|
||||
int peekLastNum = peekLast(deque);
|
||||
printf("Rear element peekLast = %d\r\n", peekLastNum);
|
||||
printf("Rear element (peekLast) = %d\r\n", peekLastNum);
|
||||
|
||||
/* Enqueue elements */
|
||||
/* Add elements to the deque */
|
||||
pushLast(deque, 4);
|
||||
printf("After enqueuing element 4 at the rear, deque = ");
|
||||
printf("After adding 4 at the rear, deque = ");
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
pushFirst(deque, 1);
|
||||
printf("After enqueuing element 1 at the front, deque = ");
|
||||
printf("After adding 1 at the front, deque = ");
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
|
||||
/* Dequeue an element */
|
||||
/* Remove elements from both ends */
|
||||
int popLastNum = popLast(deque);
|
||||
printf("Element removed from the rear = %d; after removal, deque= ", popLastNum);
|
||||
printf("Removed from the rear = %d, deque after removal = ", popLastNum);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
int popFirstNum = popFirst(deque);
|
||||
printf("Element removed from the front = %d; after removal, deque= ", popFirstNum);
|
||||
printf("Removed from the front = %d, deque after removal = ", popFirstNum);
|
||||
printArray(toArray(deque, &queSize), queSize);
|
||||
|
||||
/* Get the queue size */
|
||||
/* Get the deque size */
|
||||
int dequeSize = size(deque);
|
||||
printf("Deque size = %d\r\n", dequeSize);
|
||||
|
||||
/* Check whether the queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool isEmpty = empty(deque);
|
||||
printf("Is the queue empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
printf("Deque is empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
delArrayDeque(deque);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Queue implemented with a circular array */
|
||||
/* Queue backed by a circular array */
|
||||
typedef struct {
|
||||
int *nums; // Array that stores the queue elements
|
||||
int front; // Front pointer, pointing to the first element
|
||||
int queSize; // Current number of elements in the queue
|
||||
int front; // Index of the front element
|
||||
int queSize; // Number of elements currently in the queue
|
||||
int queCapacity; // Queue capacity
|
||||
} ArrayQueue;
|
||||
|
||||
@@ -45,30 +45,30 @@ bool empty(ArrayQueue *queue) {
|
||||
return queue->queSize == 0;
|
||||
}
|
||||
|
||||
/* Access the front element */
|
||||
/* Peek at the front element */
|
||||
int peek(ArrayQueue *queue) {
|
||||
assert(size(queue) != 0);
|
||||
return queue->nums[queue->front];
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
/* Enqueue an element */
|
||||
void push(ArrayQueue *queue, int num) {
|
||||
if (size(queue) == capacity(queue)) {
|
||||
printf("Queue is full\r\n");
|
||||
return;
|
||||
}
|
||||
// Calculate the rear pointer, which points one position past the last element
|
||||
// Use modulo to wrap rear to the beginning when it passes the end of the array
|
||||
// Compute the index one slot past the rear element
|
||||
// Use the remainder to wrap rear back to the start of the array
|
||||
int rear = (queue->front + queue->queSize) % queue->queCapacity;
|
||||
// Add num to the rear
|
||||
// Add num at the rear
|
||||
queue->nums[rear] = num;
|
||||
queue->queSize++;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
/* Remove and return the front element */
|
||||
int pop(ArrayQueue *queue) {
|
||||
int num = peek(queue);
|
||||
// Advance the front pointer by one position, wrapping to the beginning if it passes the end
|
||||
// Advance the front index by one, wrapping to the start if it passes the end
|
||||
queue->front = (queue->front + 1) % queue->queCapacity;
|
||||
queue->queSize--;
|
||||
return num;
|
||||
@@ -99,16 +99,16 @@ int main() {
|
||||
push(queue, 2);
|
||||
push(queue, 5);
|
||||
push(queue, 4);
|
||||
printf("Queue queue = ");
|
||||
printf("queue = ");
|
||||
printArray(toArray(queue, &queSize), queSize);
|
||||
|
||||
/* Access the front element */
|
||||
/* Peek at the front element */
|
||||
int peekNum = peek(queue);
|
||||
printf("Front element peek = %d\r\n", peekNum);
|
||||
printf("Front element (peek) = %d\r\n", peekNum);
|
||||
|
||||
/* Dequeue an element */
|
||||
peekNum = pop(queue);
|
||||
printf("Dequeued element pop = %d; after dequeuing, queue = ", peekNum);
|
||||
printf("Dequeued element (pop) = %d, queue after removal = ", peekNum);
|
||||
printArray(toArray(queue, &queSize), queSize);
|
||||
|
||||
/* Get the queue size */
|
||||
@@ -117,17 +117,17 @@ int main() {
|
||||
|
||||
/* Check whether the queue is empty */
|
||||
bool isEmpty = empty(queue);
|
||||
printf("Is the queue empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
printf("Queue is empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
|
||||
/* Test the circular array */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
push(queue, i);
|
||||
pop(queue);
|
||||
printf("After round %d of enqueue + dequeue, queue = ", i);
|
||||
printf("After enqueue/dequeue round %d, queue = ", i);
|
||||
printArray(toArray(queue, &queSize), queSize);
|
||||
}
|
||||
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
delArrayQueue(queue);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
#define MAX_SIZE 5000
|
||||
|
||||
/* Stack implemented with an array */
|
||||
/* Array-backed stack */
|
||||
typedef struct {
|
||||
int *data;
|
||||
int size;
|
||||
@@ -17,7 +17,7 @@ typedef struct {
|
||||
/* Constructor */
|
||||
ArrayStack *newArrayStack() {
|
||||
ArrayStack *stack = malloc(sizeof(ArrayStack));
|
||||
// Initialize with a large capacity to avoid resizing
|
||||
// Allocate a large array up front to avoid resizing
|
||||
stack->data = malloc(sizeof(int) * MAX_SIZE);
|
||||
stack->size = 0;
|
||||
return stack;
|
||||
@@ -39,7 +39,7 @@ bool isEmpty(ArrayStack *stack) {
|
||||
return stack->size == 0;
|
||||
}
|
||||
|
||||
/* Push */
|
||||
/* Push an element onto the stack */
|
||||
void push(ArrayStack *stack, int num) {
|
||||
if (stack->size == MAX_SIZE) {
|
||||
printf("Stack is full\n");
|
||||
@@ -49,7 +49,7 @@ void push(ArrayStack *stack, int num) {
|
||||
stack->size++;
|
||||
}
|
||||
|
||||
/* Access the top element */
|
||||
/* Peek at the top element */
|
||||
int peek(ArrayStack *stack) {
|
||||
if (stack->size == 0) {
|
||||
printf("Stack is empty\n");
|
||||
@@ -58,7 +58,7 @@ int peek(ArrayStack *stack) {
|
||||
return stack->data[stack->size - 1];
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
/* Remove and return the top element */
|
||||
int pop(ArrayStack *stack) {
|
||||
int val = peek(stack);
|
||||
stack->size--;
|
||||
@@ -76,27 +76,27 @@ int main() {
|
||||
push(stack, 2);
|
||||
push(stack, 5);
|
||||
push(stack, 4);
|
||||
printf("Stack stack = ");
|
||||
printf("stack = ");
|
||||
printArray(stack->data, stack->size);
|
||||
|
||||
/* Access the top element */
|
||||
/* Peek at the top element */
|
||||
int val = peek(stack);
|
||||
printf("Top element top = %d\n", val);
|
||||
printf("Top element (top) = %d\n", val);
|
||||
|
||||
/* Pop an element from the stack */
|
||||
/* Pop the top element */
|
||||
val = pop(stack);
|
||||
printf("Popped element pop = %d; after popping, stack = ", val);
|
||||
printf("Popped element (pop) = %d, stack after the pop = ", val);
|
||||
printArray(stack->data, stack->size);
|
||||
|
||||
/* Get the stack size */
|
||||
int size = stack->size;
|
||||
printf("Stack size = %d\n", size);
|
||||
|
||||
/* Check whether it is empty */
|
||||
/* Check whether the stack is empty */
|
||||
bool empty = isEmpty(stack);
|
||||
printf("Is the stack empty = %s\n", empty ? "true" : "false");
|
||||
printf("Stack is empty = %s\n", empty ? "true" : "false");
|
||||
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
delArrayStack(stack);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -27,9 +27,9 @@ void delDoublyListNode(DoublyListNode *node) {
|
||||
free(node);
|
||||
}
|
||||
|
||||
/* Deque implemented with a doubly linked list */
|
||||
/* Deque backed by a doubly linked list */
|
||||
typedef struct {
|
||||
DoublyListNode *front, *rear; // Head node front and tail node rear
|
||||
DoublyListNode *front, *rear; // front points to the head node and rear to the tail node
|
||||
int queSize; // Deque size
|
||||
} LinkedListDeque;
|
||||
|
||||
@@ -44,7 +44,7 @@ LinkedListDeque *newLinkedListDeque() {
|
||||
|
||||
/* Destructor */
|
||||
void delLinkedListdeque(LinkedListDeque *deque) {
|
||||
// Free all nodes
|
||||
// Free all the nodes
|
||||
for (int i = 0; i < deque->queSize && deque->front != NULL; i++) {
|
||||
DoublyListNode *tmp = deque->front;
|
||||
deque->front = deque->front->next;
|
||||
@@ -54,110 +54,110 @@ void delLinkedListdeque(LinkedListDeque *deque) {
|
||||
free(deque);
|
||||
}
|
||||
|
||||
/* Get the queue size */
|
||||
/* Get the deque size */
|
||||
int size(LinkedListDeque *deque) {
|
||||
return deque->queSize;
|
||||
}
|
||||
|
||||
/* Check whether the queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool empty(LinkedListDeque *deque) {
|
||||
return (size(deque) == 0);
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
/* Enqueue an element */
|
||||
void push(LinkedListDeque *deque, int num, bool isFront) {
|
||||
DoublyListNode *node = newDoublyListNode(num);
|
||||
// If the list is empty, make both front and rear point to node
|
||||
// If the list is empty, point both front and rear at node
|
||||
if (empty(deque)) {
|
||||
deque->front = deque->rear = node;
|
||||
}
|
||||
// Enqueue at the front
|
||||
// Add at the front
|
||||
else if (isFront) {
|
||||
// Add node to the head of the linked list
|
||||
// Link node at the head of the list
|
||||
deque->front->prev = node;
|
||||
node->next = deque->front;
|
||||
deque->front = node; // Update the head node
|
||||
deque->front = node; // Update the head
|
||||
}
|
||||
// Enqueue at the rear
|
||||
// Add at the rear
|
||||
else {
|
||||
// Add node to the tail of the linked list
|
||||
// Link node at the tail of the list
|
||||
deque->rear->next = node;
|
||||
node->prev = deque->rear;
|
||||
deque->rear = node;
|
||||
}
|
||||
deque->queSize++; // Update the queue size
|
||||
deque->queSize++; // Update the deque size
|
||||
}
|
||||
|
||||
/* Enqueue at the front */
|
||||
/* Add an element at the front */
|
||||
void pushFirst(LinkedListDeque *deque, int num) {
|
||||
push(deque, num, true);
|
||||
}
|
||||
|
||||
/* Enqueue at the rear */
|
||||
/* Add an element at the rear */
|
||||
void pushLast(LinkedListDeque *deque, int num) {
|
||||
push(deque, num, false);
|
||||
}
|
||||
|
||||
/* Access the front element */
|
||||
/* Peek at the front element */
|
||||
int peekFirst(LinkedListDeque *deque) {
|
||||
assert(size(deque) && deque->front);
|
||||
return deque->front->val;
|
||||
}
|
||||
|
||||
/* Access the rear element */
|
||||
/* Peek at the rear element */
|
||||
int peekLast(LinkedListDeque *deque) {
|
||||
assert(size(deque) && deque->rear);
|
||||
return deque->rear->val;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
/* Remove and return an element from either end of the deque */
|
||||
int pop(LinkedListDeque *deque, bool isFront) {
|
||||
if (empty(deque))
|
||||
return -1;
|
||||
int val;
|
||||
// When the queue size is 1, the head and tail point to the same node
|
||||
// When the deque contains one element, the head and tail point to the same node
|
||||
if (deque->queSize == 1) {
|
||||
val = deque->front->val;
|
||||
delDoublyListNode(deque->front); // Both point to the same node, so free it only once
|
||||
deque->front = NULL;
|
||||
deque->rear = NULL;
|
||||
}
|
||||
// Dequeue from the front
|
||||
// Remove from the front
|
||||
else if (isFront) {
|
||||
val = peekFirst(deque); // Save the head node value
|
||||
val = peekFirst(deque); // Save the head node's value
|
||||
DoublyListNode *fNext = deque->front->next;
|
||||
fNext->prev = NULL;
|
||||
deque->front->next = NULL;
|
||||
delDoublyListNode(deque->front);
|
||||
deque->front = fNext; // Update the head node
|
||||
deque->front = fNext; // Update the head
|
||||
}
|
||||
// Dequeue from the rear
|
||||
// Remove from the rear
|
||||
else {
|
||||
val = peekLast(deque); // Save the tail node value
|
||||
val = peekLast(deque); // Save the tail node's value
|
||||
DoublyListNode *rPrev = deque->rear->prev;
|
||||
rPrev->next = NULL;
|
||||
deque->rear->prev = NULL;
|
||||
delDoublyListNode(deque->rear);
|
||||
deque->rear = rPrev; // Update the tail node
|
||||
deque->rear = rPrev; // Update the tail
|
||||
}
|
||||
deque->queSize--; // Update the queue size
|
||||
deque->queSize--; // Update the deque size
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Dequeue from the front */
|
||||
/* Remove and return the front element */
|
||||
int popFirst(LinkedListDeque *deque) {
|
||||
return pop(deque, true);
|
||||
}
|
||||
|
||||
/* Dequeue from the rear */
|
||||
/* Remove and return the rear element */
|
||||
int popLast(LinkedListDeque *deque) {
|
||||
return pop(deque, false);
|
||||
}
|
||||
|
||||
/* Print the queue */
|
||||
/* Print the deque */
|
||||
void printLinkedListDeque(LinkedListDeque *deque) {
|
||||
int *arr = malloc(sizeof(int) * deque->queSize);
|
||||
// Copy the linked list data into an array
|
||||
// Copy the values from the linked list into an array
|
||||
int i;
|
||||
DoublyListNode *node;
|
||||
for (i = 0, node = deque->front; i < deque->queSize; i++) {
|
||||
@@ -175,40 +175,40 @@ int main() {
|
||||
pushLast(deque, 3);
|
||||
pushLast(deque, 2);
|
||||
pushLast(deque, 5);
|
||||
printf("Deque deque = ");
|
||||
printf("deque = ");
|
||||
printLinkedListDeque(deque);
|
||||
|
||||
/* Access an element */
|
||||
/* Peek at the front and rear elements */
|
||||
int peekFirstNum = peekFirst(deque);
|
||||
printf("Front element peekFirst = %d\r\n", peekFirstNum);
|
||||
printf("Front element (peekFirst) = %d\r\n", peekFirstNum);
|
||||
int peekLastNum = peekLast(deque);
|
||||
printf("Rear element peekLast = %d\r\n", peekLastNum);
|
||||
printf("Rear element (peekLast) = %d\r\n", peekLastNum);
|
||||
|
||||
/* Enqueue elements */
|
||||
/* Add elements to the deque */
|
||||
pushLast(deque, 4);
|
||||
printf("After enqueuing element 4 at the rear, deque =");
|
||||
printf("After adding 4 at the rear, deque = ");
|
||||
printLinkedListDeque(deque);
|
||||
pushFirst(deque, 1);
|
||||
printf("After enqueuing element 1 at the front, deque =");
|
||||
printf("After adding 1 at the front, deque = ");
|
||||
printLinkedListDeque(deque);
|
||||
|
||||
/* Dequeue an element */
|
||||
/* Remove elements from both ends */
|
||||
int popLastNum = popLast(deque);
|
||||
printf("Element removed from the rear, popLast = %d; after removal, deque = ", popLastNum);
|
||||
printf("Removed from the rear (popLast) = %d, deque after removal = ", popLastNum);
|
||||
printLinkedListDeque(deque);
|
||||
int popFirstNum = popFirst(deque);
|
||||
printf("Element removed from the front, popFirst = %d; after removal, deque = ", popFirstNum);
|
||||
printf("Removed from the front (popFirst) = %d, deque after removal = ", popFirstNum);
|
||||
printLinkedListDeque(deque);
|
||||
|
||||
/* Get the queue size */
|
||||
/* Get the deque size */
|
||||
int dequeSize = size(deque);
|
||||
printf("Deque size = %d\r\n", dequeSize);
|
||||
|
||||
/* Check whether the queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
bool isEmpty = empty(deque);
|
||||
printf("Is the deque empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
printf("Deque is empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
delLinkedListdeque(deque);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Queue implemented with a linked list */
|
||||
/* Queue backed by a linked list */
|
||||
typedef struct {
|
||||
ListNode *front, *rear;
|
||||
int queSize;
|
||||
@@ -23,7 +23,7 @@ LinkedListQueue *newLinkedListQueue() {
|
||||
|
||||
/* Destructor */
|
||||
void delLinkedListQueue(LinkedListQueue *queue) {
|
||||
// Free all nodes
|
||||
// Free all the nodes
|
||||
while (queue->front != NULL) {
|
||||
ListNode *tmp = queue->front;
|
||||
queue->front = queue->front->next;
|
||||
@@ -43,16 +43,16 @@ bool empty(LinkedListQueue *queue) {
|
||||
return (size(queue) == 0);
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
/* Enqueue an element */
|
||||
void push(LinkedListQueue *queue, int num) {
|
||||
// Add node at the tail
|
||||
ListNode *node = newListNode(num);
|
||||
// If the queue is empty, make both the head and tail point to this node
|
||||
// If the queue is empty, point both the head and tail at the new node
|
||||
if (queue->front == NULL) {
|
||||
queue->front = node;
|
||||
queue->rear = node;
|
||||
}
|
||||
// If the queue is not empty, add this node after the tail node
|
||||
// If the queue has elements, link the new node after the tail
|
||||
else {
|
||||
queue->rear->next = node;
|
||||
queue->rear = node;
|
||||
@@ -60,13 +60,13 @@ void push(LinkedListQueue *queue, int num) {
|
||||
queue->queSize++;
|
||||
}
|
||||
|
||||
/* Access the front element */
|
||||
/* Peek at the front element */
|
||||
int peek(LinkedListQueue *queue) {
|
||||
assert(size(queue) && queue->front);
|
||||
return queue->front->val;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
/* Remove and return the front element */
|
||||
int pop(LinkedListQueue *queue) {
|
||||
int num = peek(queue);
|
||||
ListNode *tmp = queue->front;
|
||||
@@ -79,7 +79,7 @@ int pop(LinkedListQueue *queue) {
|
||||
/* Print the queue */
|
||||
void printLinkedListQueue(LinkedListQueue *queue) {
|
||||
int *arr = malloc(sizeof(int) * queue->queSize);
|
||||
// Copy the linked list data into an array
|
||||
// Copy the values from the linked list into an array
|
||||
int i;
|
||||
ListNode *node;
|
||||
for (i = 0, node = queue->front; i < queue->queSize; i++) {
|
||||
@@ -101,16 +101,16 @@ int main() {
|
||||
push(queue, 2);
|
||||
push(queue, 5);
|
||||
push(queue, 4);
|
||||
printf("Queue queue = ");
|
||||
printf("queue = ");
|
||||
printLinkedListQueue(queue);
|
||||
|
||||
/* Access the front element */
|
||||
/* Peek at the front element */
|
||||
int peekNum = peek(queue);
|
||||
printf("Front element peek = %d\r\n", peekNum);
|
||||
printf("Front element (peek) = %d\r\n", peekNum);
|
||||
|
||||
/* Dequeue an element */
|
||||
peekNum = pop(queue);
|
||||
printf("Dequeued element pop = %d; after dequeuing, queue = ", peekNum);
|
||||
printf("Dequeued element (pop) = %d, queue after removal = ", peekNum);
|
||||
printLinkedListQueue(queue);
|
||||
|
||||
/* Get the queue size */
|
||||
@@ -119,9 +119,9 @@ int main() {
|
||||
|
||||
/* Check whether the queue is empty */
|
||||
bool isEmpty = empty(queue);
|
||||
printf("Is the queue empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
printf("Queue is empty = %s\r\n", isEmpty ? "true" : "false");
|
||||
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
delLinkedListQueue(queue);
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
#include "../utils/common.h"
|
||||
|
||||
/* Stack implemented with a linked list */
|
||||
/* Stack backed by a linked list */
|
||||
typedef struct {
|
||||
ListNode *top; // Use the head node as the stack top
|
||||
ListNode *top; // Use the head node as the top of the stack
|
||||
int size; // Stack size
|
||||
} LinkedListStack;
|
||||
|
||||
@@ -40,16 +40,16 @@ bool isEmpty(LinkedListStack *s) {
|
||||
return size(s) == 0;
|
||||
}
|
||||
|
||||
/* Push */
|
||||
/* Push an element onto the stack */
|
||||
void push(LinkedListStack *s, int num) {
|
||||
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
|
||||
node->next = s->top; // Set the new node's pointer field
|
||||
node->val = num; // Set the new node's data field
|
||||
s->top = node; // Update the stack top
|
||||
node->next = s->top; // Link the new node to the current top
|
||||
node->val = num; // Set the value of the new node
|
||||
s->top = node; // Update the top of the stack
|
||||
s->size++; // Update the stack size
|
||||
}
|
||||
|
||||
/* Access the top element */
|
||||
/* Peek at the top element */
|
||||
int peek(LinkedListStack *s) {
|
||||
if (s->size == 0) {
|
||||
printf("Stack is empty\n");
|
||||
@@ -58,12 +58,12 @@ int peek(LinkedListStack *s) {
|
||||
return s->top->val;
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
/* Remove and return the top element */
|
||||
int pop(LinkedListStack *s) {
|
||||
int val = peek(s);
|
||||
ListNode *tmp = s->top;
|
||||
s->top = s->top->next;
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
free(tmp);
|
||||
s->size--;
|
||||
return val;
|
||||
@@ -81,26 +81,26 @@ int main() {
|
||||
push(stack, 5);
|
||||
push(stack, 4);
|
||||
|
||||
printf("Stack stack = ");
|
||||
printf("stack = ");
|
||||
printLinkedList(stack->top);
|
||||
|
||||
/* Access the top element */
|
||||
/* Peek at the top element */
|
||||
int val = peek(stack);
|
||||
printf("Top element top = %d\r\n", val);
|
||||
printf("Top element (top) = %d\r\n", val);
|
||||
|
||||
/* Pop an element from the stack */
|
||||
/* Pop the top element */
|
||||
val = pop(stack);
|
||||
printf("Popped element pop = %d; after popping, stack = ", val);
|
||||
printf("Popped element (pop) = %d, stack after the pop = ", val);
|
||||
printLinkedList(stack->top);
|
||||
|
||||
/* Get the stack size */
|
||||
printf("Stack size = %d\n", size(stack));
|
||||
|
||||
/* Check whether it is empty */
|
||||
/* Check whether the stack is empty */
|
||||
bool empty = isEmpty(stack);
|
||||
printf("Is the stack empty = %s\n", empty ? "true" : "false");
|
||||
printf("Stack is empty = %s\n", empty ? "true" : "false");
|
||||
|
||||
// Free memory
|
||||
// Free the allocated memory
|
||||
delLinkedListStack(stack);
|
||||
|
||||
return 0;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user