Merge branch 'master' into feature/queue-Swift
@ -1,4 +0,0 @@
|
||||
{
|
||||
"tabWidth": 4,
|
||||
"useTabs": false
|
||||
}
|
16
Dockerfile
Normal file
@ -0,0 +1,16 @@
|
||||
FROM python:3.9.0-alpine
|
||||
|
||||
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
|
||||
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple mkdocs-material==9.0.2
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY codes /app/codes
|
||||
COPY docs /app/docs
|
||||
COPY mkdocs.yml /app/mkdocs.yml
|
||||
|
||||
RUN mkdir ./docs/overrides && mkdocs build
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["mkdocs", "serve", "-a", "0.0.0.0:8000"]
|
@ -74,11 +74,11 @@ int main() {
|
||||
int size = 5;
|
||||
int arr[5];
|
||||
printf("数组 arr = ");
|
||||
PrintArray(arr, size);
|
||||
printArray(arr, size);
|
||||
|
||||
int nums[5] = { 1, 3, 2, 5, 4 };
|
||||
printf("数组 nums = ");
|
||||
PrintArray(nums, size);
|
||||
printArray(nums, size);
|
||||
|
||||
/* 随机访问 */
|
||||
int randomNum = randomAccess(nums, size);
|
||||
@ -89,17 +89,17 @@ int main() {
|
||||
int* res = extend(nums, size, enlarge);
|
||||
size += enlarge;
|
||||
printf("将数组长度扩展至 8 ,得到 nums = ");
|
||||
PrintArray(res, size);
|
||||
printArray(res, size);
|
||||
|
||||
/* 插入元素 */
|
||||
insert(res, size, 6, 3);
|
||||
printf("在索引 3 处插入数字 6 ,得到 nums = ");
|
||||
PrintArray(res, size);
|
||||
printArray(res, size);
|
||||
|
||||
/* 删除元素 */
|
||||
removeItem(res, size, 2);
|
||||
printf("删除索引 2 处的元素,得到 nums = ");
|
||||
PrintArray(res, size);
|
||||
printArray(res, size);
|
||||
|
||||
/* 遍历数组 */
|
||||
traverse(res, size);
|
||||
|
@ -41,7 +41,7 @@ int main(int argc, char *argv[]) {
|
||||
int *nums = randomNumbers(n);
|
||||
int index = findOne(nums, n);
|
||||
printf("\n数组 [ 1, 2, ..., n ] 被打乱后 = ");
|
||||
PrintArray(nums, n);
|
||||
printArray(nums, n);
|
||||
printf("数字 1 的索引为 %d\n", index);
|
||||
// 释放堆区内存
|
||||
if (nums != NULL) {
|
||||
|
@ -7,7 +7,7 @@
|
||||
#include "../include/include.h"
|
||||
|
||||
/* 冒泡排序 */
|
||||
void bubble_sort(int nums[], int size) {
|
||||
void bubbleSort(int nums[], int size) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (int i = 0; i < size - 1; i++)
|
||||
{
|
||||
@ -25,7 +25,7 @@ void bubble_sort(int nums[], int size) {
|
||||
}
|
||||
|
||||
/* 冒泡排序(标志优化)*/
|
||||
void bubble_sort_with_flag(int nums[], int size) {
|
||||
void bubbleSortWithFlag(int nums[], int size) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (int i = 0; i < size - 1; i++)
|
||||
{
|
||||
@ -51,14 +51,14 @@ void bubble_sort_with_flag(int nums[], int size) {
|
||||
int main() {
|
||||
int nums[6] = {4, 1, 3, 1, 5, 2};
|
||||
printf("冒泡排序后: ");
|
||||
bubble_sort(nums, 6);
|
||||
bubbleSort(nums, 6);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
printf("%d ", nums[i]);
|
||||
}
|
||||
|
||||
printf("\n优化版冒泡排序后: ");
|
||||
bubble_sort_with_flag(nums, 6);
|
||||
bubbleSortWithFlag(nums, 6);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
printf("%d ", nums[i]);
|
||||
|
@ -10,34 +10,33 @@
|
||||
int main() {
|
||||
/* 初始化二叉树 */
|
||||
// 初始化结点
|
||||
TreeNode* n1 = NewTreeNode(1);
|
||||
TreeNode* n2 = NewTreeNode(2);
|
||||
TreeNode* n3 = NewTreeNode(3);
|
||||
TreeNode* n4 = NewTreeNode(4);
|
||||
TreeNode* n5 = NewTreeNode(5);
|
||||
TreeNode* n1 = newTreeNode(1);
|
||||
TreeNode* n2 = newTreeNode(2);
|
||||
TreeNode* n3 = newTreeNode(3);
|
||||
TreeNode* n4 = newTreeNode(4);
|
||||
TreeNode* n5 = newTreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1->left = n2;
|
||||
n1->right = n3;
|
||||
n2->left = n4;
|
||||
n2->right = n5;
|
||||
printf("初始化二叉树\n");
|
||||
PrintTree(n1);
|
||||
printTree(n1);
|
||||
|
||||
/* 插入与删除结点 */
|
||||
TreeNode* P = NewTreeNode(0);
|
||||
TreeNode* P = newTreeNode(0);
|
||||
// 在 n1 -> n2 中间插入结点 P
|
||||
n1->left = P;
|
||||
P->left = n2;
|
||||
printf("插入结点 P 后\n");
|
||||
PrintTree(n1);
|
||||
printTree(n1);
|
||||
|
||||
// 删除结点 P
|
||||
n1->left = n2;
|
||||
// 释放内存
|
||||
free(P);
|
||||
printf("删除结点 P 后\n");
|
||||
PrintTree(n1);
|
||||
printTree(n1);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
@ -52,15 +52,15 @@ int main() {
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
int nums[] = {1, 2, 3, NIL, 5, 6, NIL};
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
TreeNode *root = ArrayToTree(nums, size);
|
||||
TreeNode *root = arrToTree(nums, size);
|
||||
printf("初始化二叉树\n");
|
||||
PrintTree(root);
|
||||
printTree(root);
|
||||
|
||||
/* 层序遍历 */
|
||||
// 需要传入数组的长度
|
||||
int *arr = levelOrder(root, &size);
|
||||
printf("层序遍历的结点打印序列 = ");
|
||||
PrintArray(arr, size);
|
||||
printArray(arr, size);
|
||||
|
||||
return 0;
|
||||
}
|
@ -43,10 +43,10 @@ int main() {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
int nums[] = {1, 2, 3, 4, 5, 6, 7};
|
||||
int size = sizeof(nums) / sizt ceof(int);
|
||||
TreeNode *root = ArrayToTree(nums, size);
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
TreeNode *root = arrToTree(nums, size);
|
||||
printf("初始化二叉树\n");
|
||||
PrintTree(root);
|
||||
printTree(root);
|
||||
|
||||
/* 前序遍历 */
|
||||
// 初始化辅助数组
|
||||
@ -54,19 +54,19 @@ int main() {
|
||||
size = 0;
|
||||
preOrder(root, &size);
|
||||
printf("前序遍历的结点打印序列 = ");
|
||||
PrintArray(arr, size);
|
||||
printArray(arr, size);
|
||||
|
||||
/* 中序遍历 */
|
||||
size = 0;
|
||||
inOrder(root, &size);
|
||||
printf("中序遍历的结点打印序列 = ");
|
||||
PrintArray(arr, size);
|
||||
printArray(arr, size);
|
||||
|
||||
/* 后序遍历 */
|
||||
size = 0;
|
||||
postOrder(root, &size);
|
||||
printf("后序遍历的结点打印序列 = ");
|
||||
PrintArray(arr, size);
|
||||
printArray(arr, size);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
@ -9,24 +9,24 @@
|
||||
void testListNode() {
|
||||
int nums[] = {2, 3, 5, 6, 7};
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
ListNode *head = ArrayToLinkedList(nums, size);
|
||||
PrintLinkedList(head);
|
||||
ListNode *head = arrToLinkedList(nums, size);
|
||||
printLinkedList(head);
|
||||
|
||||
ListNode *node = GetListNode(head, 5);
|
||||
ListNode *node = getListNode(head, 5);
|
||||
printf("find node: %d\n", node->val);
|
||||
}
|
||||
|
||||
void testTreeNode() {
|
||||
int nums[] = {1, 2, 3, NIL, 5, 6, NIL};
|
||||
int size = sizeof(nums) / sizeof(int);
|
||||
TreeNode *root = ArrayToTree(nums, size);
|
||||
TreeNode *root = arrToTree(nums, size);
|
||||
|
||||
// print tree
|
||||
PrintTree(root);
|
||||
printTree(root);
|
||||
|
||||
// tree to arr
|
||||
int *arr = TreeToArray(root);
|
||||
PrintArray(arr, size);
|
||||
int *arr = treeToArr(root);
|
||||
printArray(arr, size);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
@ -22,7 +22,7 @@ struct ListNode {
|
||||
// typedef 为 C 语言的关键字,作用是为一种数据类型定义一个新名字
|
||||
typedef struct ListNode ListNode;
|
||||
|
||||
ListNode *NewListNode(int val) {
|
||||
ListNode *newListNode(int val) {
|
||||
ListNode *node, *next;
|
||||
node = (ListNode *) malloc(sizeof(ListNode));
|
||||
node->val = val;
|
||||
@ -37,15 +37,15 @@ ListNode *NewListNode(int val) {
|
||||
* @return ListNode*
|
||||
*/
|
||||
|
||||
ListNode *ArrayToLinkedList(const int *arr, size_t size) {
|
||||
ListNode *arrToLinkedList(const int *arr, size_t size) {
|
||||
if (size <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ListNode *dummy = NewListNode(0);
|
||||
ListNode *dummy = newListNode(0);
|
||||
ListNode *node = dummy;
|
||||
for (int i = 0; i < size; i++) {
|
||||
node->next = NewListNode(arr[i]);
|
||||
node->next = newListNode(arr[i]);
|
||||
node = node->next;
|
||||
}
|
||||
return dummy->next;
|
||||
@ -58,7 +58,7 @@ ListNode *ArrayToLinkedList(const int *arr, size_t size) {
|
||||
* @param val
|
||||
* @return ListNode*
|
||||
*/
|
||||
ListNode *GetListNode(ListNode *head, int val) {
|
||||
ListNode *getListNode(ListNode *head, int val) {
|
||||
while (head != NULL && head->val != val) {
|
||||
head = head->next;
|
||||
}
|
||||
|
@ -25,7 +25,7 @@ extern "C" {
|
||||
* @param arr
|
||||
* @param size
|
||||
*/
|
||||
static void PrintArray(int *arr, int size) {
|
||||
static void printArray(int *arr, int size) {
|
||||
printf("[");
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
if (arr[i] != NIL) {
|
||||
@ -46,7 +46,7 @@ static void PrintArray(int *arr, int size) {
|
||||
*
|
||||
* @param head
|
||||
*/
|
||||
static void PrintLinkedList(ListNode *node) {
|
||||
static void printLinkedList(ListNode *node) {
|
||||
if (node == NULL) {
|
||||
return;
|
||||
}
|
||||
@ -123,7 +123,7 @@ static void printTreeHelper(TreeNode *node, Trunk *prev, bool isLeft) {
|
||||
*
|
||||
* @param head
|
||||
*/
|
||||
static void PrintTree(TreeNode *root) {
|
||||
static void printTree(TreeNode *root) {
|
||||
printTreeHelper(root, NULL, false);
|
||||
}
|
||||
|
||||
|
@ -25,7 +25,7 @@ struct TreeNode {
|
||||
typedef struct TreeNode TreeNode;
|
||||
|
||||
|
||||
TreeNode *NewTreeNode(int val) {
|
||||
TreeNode *newTreeNode(int val) {
|
||||
TreeNode *node;
|
||||
|
||||
node = (TreeNode *) malloc(sizeof(TreeNode));
|
||||
@ -43,7 +43,7 @@ TreeNode *NewTreeNode(int val) {
|
||||
* @param size
|
||||
* @return TreeNode *
|
||||
*/
|
||||
TreeNode *ArrayToTree(const int *arr, size_t size) {
|
||||
TreeNode *arrToTree(const int *arr, size_t size) {
|
||||
if (size <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
@ -53,7 +53,7 @@ TreeNode *ArrayToTree(const int *arr, size_t size) {
|
||||
TreeNode **queue;
|
||||
|
||||
/* 根结点 */
|
||||
root = NewTreeNode(arr[0]);
|
||||
root = newTreeNode(arr[0]);
|
||||
/* 辅助队列 */
|
||||
queue = (TreeNode **) malloc(sizeof(TreeNode) * MAX_NODE_SIZE);
|
||||
// 队列指针
|
||||
@ -68,14 +68,14 @@ TreeNode *ArrayToTree(const int *arr, size_t size) {
|
||||
index++;
|
||||
if (index < size) {
|
||||
if (arr[index] != NIL) {
|
||||
node->left = NewTreeNode(arr[index]);
|
||||
node->left = newTreeNode(arr[index]);
|
||||
queue[rear++] = node->left;
|
||||
}
|
||||
}
|
||||
index++;
|
||||
if (index < size) {
|
||||
if (arr[index] != NIL) {
|
||||
node->right = NewTreeNode(arr[index]);
|
||||
node->right = newTreeNode(arr[index]);
|
||||
queue[rear++] = node->right;
|
||||
}
|
||||
}
|
||||
@ -91,7 +91,7 @@ TreeNode *ArrayToTree(const int *arr, size_t size) {
|
||||
* @param size
|
||||
* @return TreeNode *
|
||||
*/
|
||||
int *TreeToArray(TreeNode *root) {
|
||||
int *treeToArr(TreeNode *root) {
|
||||
if (root == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
@ -17,6 +17,8 @@
|
||||
#include <unordered_set>
|
||||
#include <set>
|
||||
#include <random>
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
|
||||
#include "ListNode.hpp"
|
||||
#include "TreeNode.hpp"
|
||||
|
@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
package chapter_hashing;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/* 键值对 int->String */
|
||||
|
@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
package chapter_hashing;
|
||||
|
||||
import java.util.*;
|
||||
import include.*;
|
||||
|
||||
|
67
codes/java/chapter_heap/heap.java
Normal file
@ -0,0 +1,67 @@
|
||||
/**
|
||||
* File: my_heap.java
|
||||
* Created Time: 2023-01-07
|
||||
* Author: Krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_heap;
|
||||
|
||||
import include.*;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
public class heap {
|
||||
public static void testPush(Queue<Integer> heap, int val) {
|
||||
heap.add(val); // 元素入堆
|
||||
System.out.format("\n元素 %d 入堆后\n", val);
|
||||
PrintUtil.printHeap(heap);
|
||||
}
|
||||
|
||||
public static void testPoll(Queue<Integer> heap) {
|
||||
int val = heap.poll(); // 堆顶元素出堆
|
||||
System.out.format("\n堆顶元素 %d 出堆后\n", val);
|
||||
PrintUtil.printHeap(heap);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
/* 初始化堆 */
|
||||
// 初始化小顶堆
|
||||
Queue<Integer> minHeap = new PriorityQueue<>();
|
||||
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
|
||||
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> { return b - a; });
|
||||
|
||||
System.out.println("\n以下测试样例为大顶堆");
|
||||
|
||||
/* 元素入堆 */
|
||||
testPush(maxHeap, 1);
|
||||
testPush(maxHeap, 3);
|
||||
testPush(maxHeap, 2);
|
||||
testPush(maxHeap, 5);
|
||||
testPush(maxHeap, 4);
|
||||
|
||||
/* 获取堆顶元素 */
|
||||
int peek = maxHeap.peek();
|
||||
System.out.format("\n堆顶元素为 %d\n", peek);
|
||||
|
||||
/* 堆顶元素出堆 */
|
||||
testPoll(maxHeap);
|
||||
testPoll(maxHeap);
|
||||
testPoll(maxHeap);
|
||||
testPoll(maxHeap);
|
||||
testPoll(maxHeap);
|
||||
|
||||
/* 获取堆大小 */
|
||||
int size = maxHeap.size();
|
||||
System.out.format("\n堆元素数量为 %d\n", size);
|
||||
|
||||
/* 判断堆是否为空 */
|
||||
boolean isEmpty = maxHeap.isEmpty();
|
||||
System.out.format("\n堆是否为空 %b\n", isEmpty);
|
||||
|
||||
/* 输入列表并建堆 */
|
||||
// 时间复杂度为 O(n) ,而非 O(nlogn)
|
||||
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
|
||||
System.out.println("\n输入列表并建立小顶堆后");
|
||||
PrintUtil.printHeap(minHeap);
|
||||
}
|
||||
}
|
177
codes/java/chapter_heap/my_heap.java
Normal file
@ -0,0 +1,177 @@
|
||||
/**
|
||||
* File: my_heap.java
|
||||
* Created Time: 2023-01-07
|
||||
* Author: Krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_heap;
|
||||
|
||||
import include.*;
|
||||
import java.util.*;
|
||||
|
||||
class MaxHeap {
|
||||
// 使用列表而非数组,这样无需考虑扩容问题
|
||||
private List<Integer> maxHeap;
|
||||
|
||||
/* 构造函数,建立空堆 */
|
||||
public MaxHeap() {
|
||||
maxHeap = new ArrayList<>();
|
||||
}
|
||||
|
||||
/* 构造函数,根据输入列表建堆 */
|
||||
public MaxHeap(List<Integer> nums) {
|
||||
// 所有元素入堆
|
||||
maxHeap = new ArrayList<>(nums);
|
||||
// 堆化除叶结点以外的其他所有结点
|
||||
for (int i = parent(size() - 1); i >= 0; i--) {
|
||||
siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* 获取左子结点索引 */
|
||||
private int left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* 获取右子结点索引 */
|
||||
private int right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* 获取父结点索引 */
|
||||
private int parent(int i) {
|
||||
return (i - 1) / 2; // 向下整除
|
||||
}
|
||||
|
||||
/* 交换元素 */
|
||||
private void swap(int i, int j) {
|
||||
int a = maxHeap.get(i),
|
||||
b = maxHeap.get(j),
|
||||
tmp = a;
|
||||
maxHeap.set(i, b);
|
||||
maxHeap.set(j, tmp);
|
||||
}
|
||||
|
||||
/* 获取堆大小 */
|
||||
public int size() {
|
||||
return maxHeap.size();
|
||||
}
|
||||
|
||||
/* 判断堆是否为空 */
|
||||
public boolean isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* 访问堆顶元素 */
|
||||
public int peek() {
|
||||
return maxHeap.get(0);
|
||||
}
|
||||
|
||||
/* 元素入堆 */
|
||||
public void push(int val) {
|
||||
// 添加结点
|
||||
maxHeap.add(val);
|
||||
// 从底至顶堆化
|
||||
siftUp(size() - 1);
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从底至顶堆化 */
|
||||
private void siftUp(int i) {
|
||||
while (true) {
|
||||
// 获取结点 i 的父结点
|
||||
int p = parent(i);
|
||||
// 当“越过根结点”或“结点无需修复”时,结束堆化
|
||||
if (p < 0 || maxHeap.get(i) <= maxHeap.get(p))
|
||||
break;
|
||||
// 交换两结点
|
||||
swap(i, p);
|
||||
// 循环向上堆化
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* 元素出堆 */
|
||||
public int poll() {
|
||||
// 判空处理
|
||||
if (isEmpty())
|
||||
throw new EmptyStackException();
|
||||
// 交换根结点与最右叶结点(即交换首元素与尾元素)
|
||||
swap(0, size() - 1);
|
||||
// 删除结点
|
||||
int val = maxHeap.remove(size() - 1);
|
||||
// 从顶至底堆化
|
||||
siftDown(0);
|
||||
// 返回堆顶元素
|
||||
return val;
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从顶至底堆化 */
|
||||
private void siftDown(int i) {
|
||||
while (true) {
|
||||
// 判断结点 i, l, r 中值最大的结点,记为 ma
|
||||
int l = left(i), r = right(i), ma = i;
|
||||
if (l < size() && maxHeap.get(l) > maxHeap.get(ma))
|
||||
ma = l;
|
||||
if (r < size() && maxHeap.get(r) > maxHeap.get(ma))
|
||||
ma = r;
|
||||
// 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
|
||||
if (ma == i) break;
|
||||
// 交换两结点
|
||||
swap(i, ma);
|
||||
// 循环向下堆化
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* 打印堆(二叉树) */
|
||||
public void print() {
|
||||
Queue<Integer> queue = new PriorityQueue<>((a, b) -> { return b - a; });
|
||||
queue.addAll(maxHeap);
|
||||
PrintUtil.printHeap(queue);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class my_heap {
|
||||
public static void testPush(MaxHeap maxHeap, int val) {
|
||||
maxHeap.push(val); // 元素入堆
|
||||
System.out.format("\n添加元素 %d 后\n", val);
|
||||
maxHeap.print();
|
||||
}
|
||||
|
||||
public static void testPoll(MaxHeap maxHeap) {
|
||||
int val = maxHeap.poll(); // 堆顶元素出堆
|
||||
System.out.format("\n出堆元素为 %d\n", val);
|
||||
maxHeap.print();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
/* 初始化大顶堆 */
|
||||
MaxHeap maxHeap = new MaxHeap(Arrays.asList(9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2));
|
||||
System.out.println("\n输入列表并建堆后");
|
||||
maxHeap.print();
|
||||
|
||||
/* 获取堆顶元素 */
|
||||
int peek = maxHeap.peek();
|
||||
System.out.format("\n堆顶元素为 %d\n", peek);
|
||||
|
||||
/* 元素入堆 */
|
||||
int val = 7;
|
||||
maxHeap.push(val);
|
||||
System.out.format("\n元素 %d 入堆后\n", val);
|
||||
maxHeap.print();
|
||||
|
||||
/* 堆顶元素出堆 */
|
||||
peek = maxHeap.poll();
|
||||
System.out.format("\n堆顶元素 %d 出堆后\n", peek);
|
||||
maxHeap.print();
|
||||
|
||||
/* 获取堆大小 */
|
||||
int size = maxHeap.size();
|
||||
System.out.format("\n堆元素数量为 %d\n", size);
|
||||
|
||||
/* 判断堆是否为空 */
|
||||
boolean isEmpty = maxHeap.isEmpty();
|
||||
System.out.format("\n堆是否为空 %b\n", isEmpty);
|
||||
}
|
||||
}
|
@ -30,7 +30,7 @@ public class binary_tree_bfs {
|
||||
public static void main(String[] args) {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
TreeNode root = TreeNode.arrToTree(new Integer[] { 1, 2, 3, 4, 5, 6, 7 });
|
||||
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
|
||||
System.out.println("\n初始化二叉树\n");
|
||||
PrintUtil.printTree(root);
|
||||
|
||||
|
@ -43,7 +43,7 @@ public class binary_tree_dfs {
|
||||
public static void main(String[] args) {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
TreeNode root = TreeNode.arrToTree(new Integer[] { 1, 2, 3, 4, 5, 6, 7 });
|
||||
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
|
||||
System.out.println("\n初始化二叉树\n");
|
||||
PrintUtil.printTree(root);
|
||||
|
||||
|
@ -105,10 +105,16 @@ public class PrintUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public static void printHeap(PriorityQueue<Integer> queue) {
|
||||
Integer[] nums = (Integer[])queue.toArray();
|
||||
TreeNode root = TreeNode.arrToTree(nums);
|
||||
|
||||
/**
|
||||
* Print a heap (PriorityQueue)
|
||||
* @param queue
|
||||
*/
|
||||
public static void printHeap(Queue<Integer> queue) {
|
||||
List<Integer> list = new ArrayList<>(queue);
|
||||
System.out.print("堆的数组表示:");
|
||||
System.out.println(list);
|
||||
System.out.println("堆的树状表示:");
|
||||
TreeNode root = TreeNode.listToTree(list);
|
||||
printTree(root);
|
||||
}
|
||||
}
|
||||
|
@ -23,26 +23,27 @@ public class TreeNode {
|
||||
|
||||
/**
|
||||
* Generate a binary tree given an array
|
||||
* @param arr
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
public static TreeNode arrToTree(Integer[] arr) {
|
||||
if (arr.length == 0)
|
||||
public static TreeNode listToTree(List<Integer> list) {
|
||||
int size = list.size();
|
||||
if (size == 0)
|
||||
return null;
|
||||
|
||||
TreeNode root = new TreeNode(arr[0]);
|
||||
TreeNode root = new TreeNode(list.get(0));
|
||||
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
||||
int i = 0;
|
||||
while(!queue.isEmpty()) {
|
||||
TreeNode node = queue.poll();
|
||||
if (++i >= arr.length) break;
|
||||
if(arr[i] != null) {
|
||||
node.left = new TreeNode(arr[i]);
|
||||
if (++i >= size) break;
|
||||
if (list.get(i) != null) {
|
||||
node.left = new TreeNode(list.get(i));
|
||||
queue.add(node.left);
|
||||
}
|
||||
if (++i >= arr.length) break;
|
||||
if(arr[i] != null) {
|
||||
node.right = new TreeNode(arr[i]);
|
||||
if (++i >= size) break;
|
||||
if (list.get(i) != null) {
|
||||
node.right = new TreeNode(list.get(i));
|
||||
queue.add(node.right);
|
||||
}
|
||||
}
|
||||
|
@ -64,4 +64,59 @@ pub fn build(b: *std.build.Builder) void {
|
||||
if (b.args) |args| run_cmd_leetcode_two_sum.addArgs(args);
|
||||
const run_step_leetcode_two_sum = b.step("run_leetcode_two_sum", "Run leetcode_two_sum");
|
||||
run_step_leetcode_two_sum.dependOn(&run_cmd_leetcode_two_sum.step);
|
||||
|
||||
// Section: "Array"
|
||||
// Source File: "chapter_array_and_linkedlist/array.zig"
|
||||
// Run Command: zig build run_array
|
||||
const exe_array = b.addExecutable("array", "chapter_array_and_linkedlist/array.zig");
|
||||
exe_array.addPackagePath("include", "include/include.zig");
|
||||
exe_array.setTarget(target);
|
||||
exe_array.setBuildMode(mode);
|
||||
exe_array.install();
|
||||
const run_cmd_array = exe_array.run();
|
||||
run_cmd_array.step.dependOn(b.getInstallStep());
|
||||
if (b.args) |args| run_cmd_array.addArgs(args);
|
||||
const run_step_array = b.step("run_array", "Run array");
|
||||
run_step_array.dependOn(&run_cmd_array.step);
|
||||
|
||||
// Section: "LinkedList"
|
||||
// Source File: "chapter_array_and_linkedlist/linked_list.zig"
|
||||
// Run Command: zig build run_linked_list
|
||||
const exe_linked_list = b.addExecutable("linked_list", "chapter_array_and_linkedlist/linked_list.zig");
|
||||
exe_linked_list.addPackagePath("include", "include/include.zig");
|
||||
exe_linked_list.setTarget(target);
|
||||
exe_linked_list.setBuildMode(mode);
|
||||
exe_linked_list.install();
|
||||
const run_cmd_linked_list = exe_linked_list.run();
|
||||
run_cmd_linked_list.step.dependOn(b.getInstallStep());
|
||||
if (b.args) |args| run_cmd_linked_list.addArgs(args);
|
||||
const run_step_linked_list = b.step("run_linked_list", "Run linked_list");
|
||||
run_step_linked_list.dependOn(&run_cmd_linked_list.step);
|
||||
|
||||
// Section: "List"
|
||||
// Source File: "chapter_array_and_linkedlist/list.zig"
|
||||
// Run Command: zig build run_list
|
||||
const exe_list = b.addExecutable("list", "chapter_array_and_linkedlist/list.zig");
|
||||
exe_list.addPackagePath("include", "include/include.zig");
|
||||
exe_list.setTarget(target);
|
||||
exe_list.setBuildMode(mode);
|
||||
exe_list.install();
|
||||
const run_cmd_list = exe_list.run();
|
||||
run_cmd_list.step.dependOn(b.getInstallStep());
|
||||
if (b.args) |args| run_cmd_list.addArgs(args);
|
||||
const run_step_list = b.step("run_list", "Run list");
|
||||
run_step_list.dependOn(&run_cmd_list.step);
|
||||
|
||||
// Source File: "chapter_array_and_linkedlist/my_list.zig"
|
||||
// Run Command: zig build run_my_list
|
||||
const exe_my_list = b.addExecutable("my_list", "chapter_array_and_linkedlist/my_list.zig");
|
||||
exe_my_list.addPackagePath("include", "include/include.zig");
|
||||
exe_my_list.setTarget(target);
|
||||
exe_my_list.setBuildMode(mode);
|
||||
exe_my_list.install();
|
||||
const run_cmd_my_list = exe_my_list.run();
|
||||
run_cmd_my_list.step.dependOn(b.getInstallStep());
|
||||
if (b.args) |args| run_cmd_my_list.addArgs(args);
|
||||
const run_step_my_list = b.step("run_my_list", "Run my_list");
|
||||
run_step_my_list.dependOn(&run_cmd_my_list.step);
|
||||
}
|
||||
|
117
codes/zig/chapter_array_and_linkedlist/array.zig
Normal file
@ -0,0 +1,117 @@
|
||||
// File: array.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: sjinzh (sjinzh@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 随机返回一个数组元素
|
||||
pub fn randomAccess(nums: []i32) i32 {
|
||||
// 在区间 [0, nums.len) 中随机抽取一个整数
|
||||
var randomIndex = std.crypto.random.intRangeLessThan(usize, 0, nums.len);
|
||||
// 获取并返回随机元素
|
||||
var randomNum = nums[randomIndex];
|
||||
return randomNum;
|
||||
}
|
||||
|
||||
// 扩展数组长度
|
||||
pub fn extend(mem_allocator: std.mem.Allocator, nums: []i32, enlarge: usize) ![]i32 {
|
||||
// 初始化一个扩展长度后的数组
|
||||
var res = try mem_allocator.alloc(i32, nums.len + enlarge);
|
||||
std.mem.set(i32, res, 0);
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
std.mem.copy(i32, res, nums);
|
||||
// 返回扩展后的新数组
|
||||
return res;
|
||||
}
|
||||
|
||||
// 在数组的索引 index 处插入元素 num
|
||||
pub fn insert(nums: []i32, num: i32, index: usize) void {
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
var i = nums.len - 1;
|
||||
while (i > index) : (i -= 1) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
// 删除索引 index 处元素
|
||||
pub fn remove(nums: []i32, index: usize) void {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
var i = index;
|
||||
while (i < nums.len - 1) : (i += 1) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
// 遍历数组
|
||||
pub fn traverse(nums: []i32) void {
|
||||
var count: i32 = 0;
|
||||
// 通过索引遍历数组
|
||||
var i: i32 = 0;
|
||||
while (i < nums.len) : (i += 1) {
|
||||
count += 1;
|
||||
}
|
||||
count = 0;
|
||||
// 直接遍历数组
|
||||
for (nums) |_| {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 在数组中查找指定元素
|
||||
pub fn find(nums: []i32, target: i32) i32 {
|
||||
for (nums) |num, i| {
|
||||
if (num == target) return @intCast(i32, i);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化数组
|
||||
const size: i32 = 5;
|
||||
var arr = [_]i32{0} ** size;
|
||||
std.debug.print("数组 arr = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &arr);
|
||||
|
||||
var array = [_]i32{ 1, 3, 2, 5, 4 };
|
||||
std.debug.print("\n数组 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &array);
|
||||
|
||||
// 随机访问
|
||||
var randomNum = randomAccess(&array);
|
||||
std.debug.print("\n在 nums 中获取随机元素 {}", .{randomNum});
|
||||
|
||||
// 长度扩展
|
||||
var known_at_runtime_zero: usize = 0;
|
||||
var nums: []i32 = array[known_at_runtime_zero..array.len];
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
nums = try extend(mem_allocator, nums, 3);
|
||||
std.debug.print("\n将数组长度扩展至 8 ,得到 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, nums);
|
||||
|
||||
// 插入元素
|
||||
insert(nums, 6, 3);
|
||||
std.debug.print("\n在索引 3 处插入数字 6 ,得到 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, nums);
|
||||
|
||||
// 删除元素
|
||||
remove(nums, 2);
|
||||
std.debug.print("\n删除索引 2 处的元素,得到 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, nums);
|
||||
|
||||
// 遍历数组
|
||||
traverse(nums);
|
||||
|
||||
// 查找元素
|
||||
var index = find(nums, 3);
|
||||
std.debug.print("\n在 nums 中查找元素 3 ,得到索引 = {}\n", .{index});
|
||||
|
||||
const getchar = try std.io.getStdIn().reader().readByte();
|
||||
_ = getchar;
|
||||
}
|
||||
|
85
codes/zig/chapter_array_and_linkedlist/linked_list.zig
Normal file
@ -0,0 +1,85 @@
|
||||
// File: linked_list.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: sjinzh (sjinzh@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 在链表的结点 n0 之后插入结点 P
|
||||
pub fn insert(n0: ?*inc.ListNode(i32), P: ?*inc.ListNode(i32)) void {
|
||||
var n1 = n0.?.next;
|
||||
n0.?.next = P;
|
||||
P.?.next = n1;
|
||||
}
|
||||
|
||||
// 删除链表的结点 n0 之后的首个结点
|
||||
pub fn remove(n0: ?*inc.ListNode(i32)) void {
|
||||
if (n0.?.next == null) return;
|
||||
// n0 -> P -> n1
|
||||
var P = n0.?.next;
|
||||
var n1 = P.?.next;
|
||||
n0.?.next = n1;
|
||||
}
|
||||
|
||||
// 访问链表中索引为 index 的结点
|
||||
pub fn access(node: ?*inc.ListNode(i32), index: i32) ?*inc.ListNode(i32) {
|
||||
var head = node;
|
||||
var i: i32 = 0;
|
||||
while (i < index) : (i += 1) {
|
||||
head = head.?.next;
|
||||
if (head == null) return null;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
// 在链表中查找值为 target 的首个结点
|
||||
pub fn find(node: ?*inc.ListNode(i32), target: i32) i32 {
|
||||
var head = node;
|
||||
var index: i32 = 0;
|
||||
while (head != null) {
|
||||
if (head.?.val == target) return index;
|
||||
head = head.?.next;
|
||||
index += 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化链表
|
||||
// 初始化各个结点
|
||||
var n0 = inc.ListNode(i32){.val = 1};
|
||||
var n1 = inc.ListNode(i32){.val = 3};
|
||||
var n2 = inc.ListNode(i32){.val = 2};
|
||||
var n3 = inc.ListNode(i32){.val = 5};
|
||||
var n4 = inc.ListNode(i32){.val = 4};
|
||||
// 构建引用指向
|
||||
n0.next = &n1;
|
||||
n1.next = &n2;
|
||||
n2.next = &n3;
|
||||
n3.next = &n4;
|
||||
std.debug.print("初始化的链表为", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, &n0);
|
||||
|
||||
// 插入结点
|
||||
var tmp = inc.ListNode(i32){.val = 0};
|
||||
insert(&n0, &tmp);
|
||||
std.debug.print("插入结点后的链表为", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, &n0);
|
||||
|
||||
// 删除结点
|
||||
remove(&n0);
|
||||
std.debug.print("删除结点后的链表为", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, &n0);
|
||||
|
||||
// 访问结点
|
||||
var node = access(&n0, 3);
|
||||
std.debug.print("链表中索引 3 处的结点的值 = {}\n", .{node.?.val});
|
||||
|
||||
// 查找结点
|
||||
var index = find(&n0, 2);
|
||||
std.debug.print("链表中值为 2 的结点的索引 = {}\n", .{index});
|
||||
|
||||
const getchar = try std.io.getStdIn().reader().readByte();
|
||||
_ = getchar;
|
||||
}
|
81
codes/zig/chapter_array_and_linkedlist/list.zig
Normal file
@ -0,0 +1,81 @@
|
||||
// File: list.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: sjinzh (sjinzh@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化列表
|
||||
var list = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
// 延迟释放内存
|
||||
defer list.deinit();
|
||||
try list.appendSlice(&[_]i32{ 1, 3, 2, 5, 4 });
|
||||
std.debug.print("列表 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 访问元素
|
||||
var num = list.items[1];
|
||||
std.debug.print("\n访问索引 1 处的元素,得到 num = {}", .{num});
|
||||
|
||||
// 更新元素
|
||||
list.items[1] = 0;
|
||||
std.debug.print("\n将索引 1 处的元素更新为 0 ,得到 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 清空列表
|
||||
list.clearRetainingCapacity();
|
||||
std.debug.print("\n清空列表后 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 尾部添加元素
|
||||
try list.append(1);
|
||||
try list.append(3);
|
||||
try list.append(2);
|
||||
try list.append(5);
|
||||
try list.append(4);
|
||||
std.debug.print("\n添加元素后 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 中间插入元素
|
||||
try list.insert(3, 6);
|
||||
std.debug.print("\n在索引 3 处插入数字 6 ,得到 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 删除元素
|
||||
var value = list.orderedRemove(3);
|
||||
_ = value;
|
||||
std.debug.print("\n删除索引 3 处的元素,得到 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 通过索引遍历列表
|
||||
var count: i32 = 0;
|
||||
var i: i32 = 0;
|
||||
while (i < list.items.len) : (i += 1) {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
// 直接遍历列表元素
|
||||
count = 0;
|
||||
for (list.items) |_| {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
// 拼接两个列表
|
||||
var list1 = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer list1.deinit();
|
||||
try list1.appendSlice(&[_]i32{ 6, 8, 7, 10, 9 });
|
||||
try list.insertSlice(list.items.len, list1.items);
|
||||
std.debug.print("\n将列表 list1 拼接到 list 之后,得到 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 排序列表
|
||||
std.sort.sort(i32, list.items, {}, comptime std.sort.asc(i32));
|
||||
std.debug.print("\n排序列表后 list = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
const getchar = try std.io.getStdIn().reader().readByte();
|
||||
_ = getchar;
|
||||
}
|
||||
|
177
codes/zig/chapter_array_and_linkedlist/my_list.zig
Normal file
@ -0,0 +1,177 @@
|
||||
// File: my_list.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: sjinzh (sjinzh@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 列表类简易实现
|
||||
// 编译期泛型
|
||||
pub fn MyList(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
nums: []T = undefined, // 数组(存储列表元素)
|
||||
numsCapacity: usize = 10, // 列表容量
|
||||
numSize: usize = 0, // 列表长度(即当前元素数量)
|
||||
extendRatio: usize = 2, // 每次列表扩容的倍数
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造函数(分配内存+初始化列表)
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.nums = try self.mem_allocator.alloc(T, self.numsCapacity);
|
||||
std.mem.set(T, self.nums, @as(T, 0));
|
||||
}
|
||||
|
||||
// 析构函数(释放内存)
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 获取列表长度(即当前元素数量)
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.numSize;
|
||||
}
|
||||
|
||||
// 获取列表容量
|
||||
pub fn capacity(self: *Self) usize {
|
||||
return self.numsCapacity;
|
||||
}
|
||||
|
||||
// 访问元素
|
||||
pub fn get(self: *Self, index: usize) T {
|
||||
// 索引如果越界则抛出异常,下同
|
||||
if (index >= self.size()) @panic("索引越界");
|
||||
return self.nums[index];
|
||||
}
|
||||
|
||||
// 更新元素
|
||||
pub fn set(self: *Self, index: usize, num: T) void {
|
||||
// 索引如果越界则抛出异常,下同
|
||||
if (index >= self.size()) @panic("索引越界");
|
||||
self.nums[index] = num;
|
||||
}
|
||||
|
||||
// 尾部添加元素
|
||||
pub fn add(self: *Self, num: T) !void {
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (self.size() == self.capacity()) try self.extendCapacity();
|
||||
self.nums[self.size()] = num;
|
||||
// 更新元素数量
|
||||
self.numSize += 1;
|
||||
}
|
||||
|
||||
// 中间插入元素
|
||||
pub fn insert(self: *Self, index: usize, num: T) !void {
|
||||
if (index >= self.size()) @panic("索引越界");
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (self.size() == self.capacity()) try self.extendCapacity();
|
||||
// 索引 i 以及之后的元素都向后移动一位
|
||||
var j = self.size() - 1;
|
||||
while (j >= index) : (j -= 1) {
|
||||
self.nums[j + 1] = self.nums[j];
|
||||
}
|
||||
self.nums[index] = num;
|
||||
// 更新元素数量
|
||||
self.numSize += 1;
|
||||
}
|
||||
|
||||
// 删除元素
|
||||
pub fn remove(self: *Self, index: usize) T {
|
||||
if (index >= self.size()) @panic("索引越界");
|
||||
var num = self.nums[index];
|
||||
// 索引 i 之后的元素都向前移动一位
|
||||
var j = index;
|
||||
while (j < self.size() - 1) : (j += 1) {
|
||||
self.nums[j] = self.nums[j + 1];
|
||||
}
|
||||
// 更新元素数量
|
||||
self.numSize -= 1;
|
||||
// 返回被删除元素
|
||||
return num;
|
||||
}
|
||||
|
||||
// 列表扩容
|
||||
pub fn extendCapacity(self: *Self) !void {
|
||||
// 新建一个长度为 size * extendRatio 的数组,并将原数组拷贝到新数组
|
||||
var newCapacity = self.capacity() * self.extendRatio;
|
||||
var extend = try self.mem_allocator.alloc(T, newCapacity);
|
||||
std.mem.set(T, extend, @as(T, 0));
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
std.mem.copy(T, extend, self.nums);
|
||||
self.nums = extend;
|
||||
// 更新列表容量
|
||||
self.numsCapacity = newCapacity;
|
||||
}
|
||||
|
||||
// 将列表转换为数组
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
// 仅转换有效长度范围内的列表元素
|
||||
var nums = try self.mem_allocator.alloc(T, self.size());
|
||||
std.mem.set(T, nums, @as(T, 0));
|
||||
for (nums) |*num, i| {
|
||||
num.* = self.get(i);
|
||||
}
|
||||
return nums;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化列表
|
||||
var list = MyList(i32){};
|
||||
try list.init(std.heap.page_allocator);
|
||||
// 延迟释放内存
|
||||
defer list.deinit();
|
||||
|
||||
// 尾部添加元素
|
||||
try list.add(1);
|
||||
try list.add(3);
|
||||
try list.add(2);
|
||||
try list.add(5);
|
||||
try list.add(4);
|
||||
std.debug.print("列表 list = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try list.toArray());
|
||||
std.debug.print(" ,容量 = {} ,长度 = {}", .{list.capacity(), list.size()});
|
||||
|
||||
// 中间插入元素
|
||||
try list.insert(3, 6);
|
||||
std.debug.print("\n在索引 3 处插入数字 6 ,得到 list = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try list.toArray());
|
||||
|
||||
// 删除元素
|
||||
_ = list.remove(3);
|
||||
std.debug.print("\n删除索引 3 处的元素,得到 list = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try list.toArray());
|
||||
|
||||
// 访问元素
|
||||
var num = list.get(1);
|
||||
std.debug.print("\n访问索引 1 处的元素,得到 num = {}", .{num});
|
||||
|
||||
// 更新元素
|
||||
list.set(1, 0);
|
||||
std.debug.print("\n将索引 1 处的元素更新为 0 ,得到 list = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try list.toArray());
|
||||
|
||||
// 测试扩容机制
|
||||
list.set(1, 0);
|
||||
var i: i32 = 0;
|
||||
while (i < 10) : (i += 1) {
|
||||
// 在 i = 5 时,列表长度将超出列表容量,此时触发扩容机制
|
||||
try list.add(i);
|
||||
}
|
||||
std.debug.print("\n扩容后的列表 list = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try list.toArray());
|
||||
std.debug.print(" ,容量 = {} ,长度 = {}\n", .{list.capacity(), list.size()});
|
||||
|
||||
const getchar = try std.io.getStdIn().reader().readByte();
|
||||
_ = getchar;
|
||||
}
|
||||
|
@ -7,16 +7,42 @@ const ListNode = @import("ListNode.zig").ListNode;
|
||||
const TreeNode = @import("TreeNode.zig").TreeNode;
|
||||
|
||||
// Print an array
|
||||
// 编译期泛型
|
||||
pub fn printArray(comptime T: type, nums: []T) void {
|
||||
std.debug.print("[", .{});
|
||||
if (nums.len > 0) {
|
||||
for (nums) |num, j| {
|
||||
std.debug.print("{}{s}", .{num, if (j == nums.len-1) "]\n" else ", " });
|
||||
std.debug.print("{}{s}", .{num, if (j == nums.len-1) "]" else ", " });
|
||||
}
|
||||
} else {
|
||||
std.debug.print("]", .{});
|
||||
std.debug.print("\n", .{});
|
||||
}
|
||||
}
|
||||
|
||||
// Print a list
|
||||
pub fn printList(comptime T: type, list: std.ArrayList(T)) void {
|
||||
std.debug.print("[", .{});
|
||||
if (list.items.len > 0) {
|
||||
for (list.items) |value, i| {
|
||||
std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "]" else ", " });
|
||||
}
|
||||
} else {
|
||||
std.debug.print("]", .{});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Print a linked list
|
||||
pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
|
||||
if (node == null) return;
|
||||
var list = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer list.deinit();
|
||||
var head = node;
|
||||
while (head != null) {
|
||||
try list.append(head.?.val);
|
||||
head = head.?.next;
|
||||
}
|
||||
for (list.items) |value, i| {
|
||||
std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "\n" else "->" });
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -3,6 +3,6 @@ mkdocs build --clean
|
||||
cd site
|
||||
git init
|
||||
git add -A
|
||||
git commit -m 'deploy'
|
||||
git commit -m "deploy"
|
||||
git push -f git@github.com:krahets/hello-algo.git master:gh-pages
|
||||
cd -
|
||||
|
7
docker-compose.yml
Normal file
@ -0,0 +1,7 @@
|
||||
version: '3'
|
||||
services:
|
||||
hello-algo:
|
||||
build: .
|
||||
ports:
|
||||
- "8000:8000"
|
||||
|
BIN
docs/chapter_heap/heap.assets/heap_poll_step1.png
Normal file
After Width: | Height: | Size: 69 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step10.png
Normal file
After Width: | Height: | Size: 89 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step2.png
Normal file
After Width: | Height: | Size: 66 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step3.png
Normal file
After Width: | Height: | Size: 69 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step4.png
Normal file
After Width: | Height: | Size: 81 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step5.png
Normal file
After Width: | Height: | Size: 89 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step6.png
Normal file
After Width: | Height: | Size: 85 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step7.png
Normal file
After Width: | Height: | Size: 94 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step8.png
Normal file
After Width: | Height: | Size: 87 KiB |
BIN
docs/chapter_heap/heap.assets/heap_poll_step9.png
Normal file
After Width: | Height: | Size: 96 KiB |
BIN
docs/chapter_heap/heap.assets/heap_push_step1.png
Normal file
After Width: | Height: | Size: 69 KiB |
BIN
docs/chapter_heap/heap.assets/heap_push_step2.png
Normal file
After Width: | Height: | Size: 66 KiB |
BIN
docs/chapter_heap/heap.assets/heap_push_step3.png
Normal file
After Width: | Height: | Size: 81 KiB |
BIN
docs/chapter_heap/heap.assets/heap_push_step4.png
Normal file
After Width: | Height: | Size: 84 KiB |
BIN
docs/chapter_heap/heap.assets/heap_push_step5.png
Normal file
After Width: | Height: | Size: 85 KiB |
BIN
docs/chapter_heap/heap.assets/heap_push_step6.png
Normal file
After Width: | Height: | Size: 85 KiB |
BIN
docs/chapter_heap/heap.assets/heapify_count.png
Normal file
After Width: | Height: | Size: 64 KiB |
BIN
docs/chapter_heap/heap.assets/min_heap_and_max_heap.png
Normal file
After Width: | Height: | Size: 80 KiB |
BIN
docs/chapter_heap/heap.assets/representation_of_heap.png
Normal file
After Width: | Height: | Size: 113 KiB |
627
docs/chapter_heap/heap.md
Normal file
@ -0,0 +1,627 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 堆
|
||||
|
||||
「堆 Heap」是一颗限定条件下的「完全二叉树」。根据成立条件,堆主要分为两种类型:
|
||||
|
||||
- 「大顶堆 Max Heap」,任意结点的值 $\geq$ 其子结点的值;
|
||||
- 「小顶堆 Min Heap」,任意结点的值 $\leq$ 其子结点的值;
|
||||
|
||||

|
||||
|
||||
## 堆术语与性质
|
||||
|
||||
- 由于堆是完全二叉树,因此最底层结点靠左填充,其它层结点皆被填满。
|
||||
- 二叉树中的根结点对应「堆顶」,底层最靠右结点对应「堆底」。
|
||||
- 对于大顶堆 / 小顶堆,其堆顶元素(即根结点)的值最大 / 最小。
|
||||
|
||||
## 堆常用操作
|
||||
|
||||
值得说明的是,多数编程语言提供的是「优先队列 Priority Queue」,其是一种抽象数据结构,**定义为具有出队优先级的队列**。
|
||||
|
||||
而恰好,**堆的定义与优先队列的操作逻辑完全吻合**,大顶堆就是一个元素从大到小出队的优先队列。从使用角度看,我们可以将「优先队列」和「堆」理解为等价的数据结构。因此,本文与代码对两者不做特别区分,统一使用「堆」来命名。
|
||||
|
||||
堆的常用操作见下表(方法命名以 Java 为例)。
|
||||
|
||||
<p align="center"> Table. 堆的常用操作 </p>
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| 方法 | 描述 | 时间复杂度 |
|
||||
| --------- | -------------------------------------------- | ----------- |
|
||||
| add() | 元素入堆 | $O(\log n)$ |
|
||||
| poll() | 堆顶元素出堆 | $O(\log n)$ |
|
||||
| peek() | 访问堆顶元素(大 / 小顶堆分别为最大 / 小值) | $O(1)$ |
|
||||
| size() | 获取堆的元素数量 | $O(1)$ |
|
||||
| isEmpty() | 判断堆是否为空 | $O(1)$ |
|
||||
|
||||
</div>
|
||||
|
||||
我们可以直接使用编程语言提供的堆类(或优先队列类)。
|
||||
|
||||
!!! tip
|
||||
|
||||
类似于排序中“从小到大排列”和“从大到小排列”,“大顶堆”和“小顶堆”可仅通过修改 Comparator 来互相转换。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="heap.java"
|
||||
/* 初始化堆 */
|
||||
// 初始化小顶堆
|
||||
Queue<Integer> minHeap = new PriorityQueue<>();
|
||||
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
|
||||
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> { return b - a; });
|
||||
|
||||
/* 元素入堆 */
|
||||
maxHeap.add(1);
|
||||
maxHeap.add(3);
|
||||
maxHeap.add(2);
|
||||
maxHeap.add(5);
|
||||
maxHeap.add(4);
|
||||
|
||||
/* 获取堆顶元素 */
|
||||
int peek = maxHeap.peek(); // 5
|
||||
|
||||
/* 堆顶元素出堆 */
|
||||
// 出堆元素会形成一个从大到小的序列
|
||||
peek = heap.poll(); // 5
|
||||
peek = heap.poll(); // 4
|
||||
peek = heap.poll(); // 3
|
||||
peek = heap.poll(); // 2
|
||||
peek = heap.poll(); // 1
|
||||
|
||||
/* 获取堆大小 */
|
||||
int size = maxHeap.size();
|
||||
|
||||
/* 判断堆是否为空 */
|
||||
boolean isEmpty = maxHeap.isEmpty();
|
||||
|
||||
/* 输入列表并建堆 */
|
||||
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="heap.cpp"
|
||||
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="heap.py"
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="heap.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="heap.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="heap.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="heap.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="heap.cs"
|
||||
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="heap.swift"
|
||||
|
||||
```
|
||||
|
||||
## 堆的实现
|
||||
|
||||
下文实现的是「大顶堆」,若想转换为「小顶堆」,将所有大小逻辑判断取逆(例如将 $\geq$ 替换为 $\leq$ )即可,有兴趣的同学可自行实现。
|
||||
|
||||
### 堆的存储与表示
|
||||
|
||||
在二叉树章节我们学过,「完全二叉树」非常适合使用「数组」来表示,而堆恰好是一颗完全二叉树,**因而我们采用「数组」来存储「堆」**。
|
||||
|
||||
**二叉树指针**。使用数组表示二叉树时,元素代表结点值,索引代表结点在二叉树中的位置,**而结点指针通过索引映射公式来实现**。
|
||||
|
||||
具体地,给定索引 $i$ ,那么其左子结点索引为 $2i + 1$ 、右子结点索引为 $2i + 2$ 、父结点索引为 $(i - 1) / 2$ (向下整除)。当索引越界时,代表空结点或结点不存在。
|
||||
|
||||

|
||||
|
||||
我们将索引映射公式封装成函数,以便后续使用。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="my_heap.java"
|
||||
// 使用列表而非数组,这样无需考虑扩容问题
|
||||
List<Integer> maxHeap;
|
||||
|
||||
/* 构造函数,建立空堆 */
|
||||
public MaxHeap() {
|
||||
maxHeap = new ArrayList<>();
|
||||
}
|
||||
|
||||
/* 获取左子结点索引 */
|
||||
int left(int i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* 获取右子结点索引 */
|
||||
int right(int i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* 获取父结点索引 */
|
||||
int parent(int i) {
|
||||
return (i - 1) / 2; // 向下整除
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="my_heap.py"
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="my_heap.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="my_heap.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="my_heap.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="my_heap.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_heap.cs"
|
||||
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="my_heap.swift"
|
||||
|
||||
```
|
||||
|
||||
### 访问堆顶元素
|
||||
|
||||
堆顶元素是二叉树的根结点,即列表首元素。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="my_heap.java"
|
||||
/* 访问堆顶元素 */
|
||||
public int peek() {
|
||||
return maxHeap.get(0);
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="my_heap.py"
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="my_heap.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="my_heap.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="my_heap.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="my_heap.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_heap.cs"
|
||||
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="my_heap.swift"
|
||||
|
||||
```
|
||||
|
||||
### 元素入堆
|
||||
|
||||
给定元素 `val` ,我们先将其添加到堆底。添加后,由于 `val` 可能大于堆中其它元素,此时堆的成立条件可能已经被破坏,**因此需要修复从插入结点到根结点这条路径上的各个结点**,该操作被称为「堆化 Heapify」。
|
||||
|
||||
考虑从入堆结点开始,**从底至顶执行堆化**。具体地,比较插入结点与其父结点的值,若插入结点更大则将它们交换;并循环以上操作,从底至顶地修复堆中的各个结点;直至越过根结点时结束,或当遇到无需交换的结点时提前结束。
|
||||
|
||||
=== "Step 1"
|
||||

|
||||
|
||||
=== "Step 2"
|
||||

|
||||
|
||||
=== "Step 3"
|
||||

|
||||
|
||||
=== "Step 4"
|
||||

|
||||
|
||||
=== "Step 5"
|
||||

|
||||
|
||||
=== "Step 6"
|
||||

|
||||
|
||||
设结点总数为 $n$ ,则树的高度为 $O(\log n)$ ,易得堆化操作的循环轮数最多为 $O(\log n)$ ,**因而元素入堆操作的时间复杂度为 $O(\log n)$** 。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="my_heap.java"
|
||||
/* 元素入堆 */
|
||||
void push(int val) {
|
||||
// 添加结点
|
||||
maxHeap.add(val);
|
||||
// 从底至顶堆化
|
||||
siftUp(size() - 1);
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从底至顶堆化 */
|
||||
void siftUp(int i) {
|
||||
while (true) {
|
||||
// 获取结点 i 的父结点
|
||||
int p = parent(i);
|
||||
// 若“越过根结点”或“结点无需修复”,则结束堆化
|
||||
if (p < 0 || maxHeap.get(i) <= maxHeap.get(p))
|
||||
break;
|
||||
// 交换两结点
|
||||
swap(i, p);
|
||||
// 循环向上堆化
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="my_heap.py"
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="my_heap.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="my_heap.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="my_heap.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="my_heap.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_heap.cs"
|
||||
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="my_heap.swift"
|
||||
|
||||
```
|
||||
|
||||
### 堆顶元素出堆
|
||||
|
||||
堆顶元素是二叉树根结点,即列表首元素,如果我们直接将首元素从列表中删除,则二叉树中所有结点都会随之发生移位(索引发生变化),这样后续使用堆化修复就很麻烦了。为了尽量减少元素索引变动,采取以下操作步骤:
|
||||
|
||||
1. 交换堆顶元素与堆底元素(即交换根结点与最右叶结点);
|
||||
2. 交换完成后,将堆底从列表中删除(注意,因为已经交换,实际上删除的是原来的堆顶元素);
|
||||
3. 从根结点开始,**从顶至底执行堆化**;
|
||||
|
||||
顾名思义,**从顶至底堆化的操作方向与从底至顶堆化相反**,我们比较根结点的值与其两个子结点的值,将最大的子结点与根结点执行交换,并循环以上操作,直到越过叶结点时结束,或当遇到无需交换的结点时提前结束。
|
||||
|
||||
=== "Step 1"
|
||||

|
||||
|
||||
=== "Step 2"
|
||||

|
||||
|
||||
=== "Step 3"
|
||||

|
||||
|
||||
=== "Step 4"
|
||||

|
||||
|
||||
=== "Step 5"
|
||||

|
||||
|
||||
=== "Step 6"
|
||||

|
||||
|
||||
=== "Step 7"
|
||||

|
||||
|
||||
=== "Step 8"
|
||||

|
||||
|
||||
=== "Step 9"
|
||||

|
||||
|
||||
=== "Step 10"
|
||||

|
||||
|
||||
与元素入堆操作类似,**堆顶元素出堆操作的时间复杂度为 $O(\log n)$** 。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="my_heap.java"
|
||||
/* 元素出堆 */
|
||||
int poll() {
|
||||
// 判空处理
|
||||
if (isEmpty())
|
||||
throw new EmptyStackException();
|
||||
// 交换根结点与最右叶结点(即交换首元素与尾元素)
|
||||
swap(0, size() - 1);
|
||||
// 删除结点
|
||||
int val = maxHeap.remove(size() - 1);
|
||||
// 从顶至底堆化
|
||||
siftDown(0);
|
||||
// 返回堆顶元素
|
||||
return val;
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从顶至底堆化 */
|
||||
void siftDown(int i) {
|
||||
while (true) {
|
||||
// 判断结点 i, l, r 中值最大的结点,记为 ma
|
||||
int l = left(i), r = right(i), ma = i;
|
||||
if (l < size() && maxHeap.get(l) > maxHeap.get(ma))
|
||||
ma = l;
|
||||
if (r < size() && maxHeap.get(r) > maxHeap.get(ma))
|
||||
ma = r;
|
||||
// 若“结点 i 最大”或“越过叶结点”,则结束堆化
|
||||
if (ma == i) break;
|
||||
// 交换两结点
|
||||
swap(i, ma);
|
||||
// 循环向下堆化
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="my_heap.py"
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="my_heap.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="my_heap.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="my_heap.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="my_heap.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_heap.cs"
|
||||
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="my_heap.swift"
|
||||
|
||||
```
|
||||
|
||||
### 输入数据并建堆 *
|
||||
|
||||
如果我们想要直接输入一个列表并将其建堆,那么该怎么做呢?最直接地,考虑使用「元素入堆」方法,将列表元素依次入堆。元素入堆的时间复杂度为 $O(n)$ ,而平均长度为 $\frac{n}{2}$ ,因此该方法的总体时间复杂度为 $O(n \log n)$ 。
|
||||
|
||||
然而,存在一种更加优雅的建堆方法。设结点数量为 $n$ ,我们先将列表所有元素原封不动添加进堆,**然后迭代地对各个结点执行「从顶至底堆化」**。当然,**无需对叶结点执行堆化**,因为其没有子结点。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="my_heap.java"
|
||||
/* 构造函数,根据输入列表建堆 */
|
||||
public MaxHeap(List<Integer> nums) {
|
||||
// 将列表元素原封不动添加进堆
|
||||
maxHeap = new ArrayList<>(nums);
|
||||
// 堆化除叶结点以外的其他所有结点
|
||||
for (int i = parent(size() - 1); i >= 0; i--) {
|
||||
siftDown(i);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="my_heap.cpp"
|
||||
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="my_heap.py"
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="my_heap.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="my_heap.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="my_heap.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="my_heap.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_heap.cs"
|
||||
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="my_heap.swift"
|
||||
|
||||
```
|
||||
|
||||
那么,第二种建堆方法的时间复杂度时多少呢?我们来做一下简单推算。
|
||||
|
||||
- 完全二叉树中,设结点总数为 $n$ ,则叶结点数量为 $(n + 1) / 2$ ,其中 $/$ 为向下整除。因此在排除叶结点后,需要堆化结点数量为 $(n - 1)/2$ ,即为 $O(n)$ ;
|
||||
- 从顶至底堆化中,每个结点最多堆化至叶结点,因此最大迭代次数为二叉树高度 $O(\log n)$ ;
|
||||
|
||||
将上述两者相乘,可得时间复杂度为 $O(n \log n)$ 。然而,该估算结果仍不够准确,因为我们没有考虑到 **二叉树底层结点远多于顶层结点** 的性质。
|
||||
|
||||
下面我们来尝试展开计算。为了减小计算难度,我们假设树是一个「完美二叉树」,该假设不会影响计算结果的正确性。设二叉树(即堆)结点数量为 $n$ ,树高度为 $h$ 。上文提到,**结点堆化最大迭代次数等于该结点到叶结点的距离,而这正是“结点高度”**。因此,我们将各层的“结点数量 $\times$ 结点高度”求和,即可得到所有结点的堆化的迭代次数总和。
|
||||
|
||||
$$
|
||||
T(h) = 2^0h + 2^1(h-1) + 2^2(h-2) + \cdots + 2^{(h-1)}\times1
|
||||
$$
|
||||
|
||||

|
||||
|
||||
化简上式需要借助中学的数列知识,先对 $T(h)$ 乘以 $2$ ,易得
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
T(h) & = 2^0h + 2^1(h-1) + 2^2(h-2) + \cdots + 2^{h-1}\times1 \newline
|
||||
2 T(h) & = 2^1h + 2^2(h-1) + 2^3(h-2) + \cdots + 2^{h}\times1 \newline
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
**使用错位相减法**,令下式 $2 T(h)$ 减去上式 $T(h)$ ,可得
|
||||
|
||||
$$
|
||||
2T(h) - T(h) = T(h) = -2^0h + 2^1 + 2^2 + \cdots + 2^{h-1} + 2^h
|
||||
$$
|
||||
|
||||
观察上式,$T(h)$ 是一个等比数列,可直接使用求和公式,得到时间复杂度为
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
T(h) & = 2 \frac{1 - 2^h}{1 - 2} - h \newline
|
||||
& = 2^{h+1} - h \newline
|
||||
& = O(2^h)
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
进一步地,高度为 $h$ 的完美二叉树的结点数量为 $n = 2^{h+1} - 1$ ,易得复杂度为 $O(2^h) = O(n)$。以上推算表明,**输入列表并建堆的时间复杂度为 $O(n)$ ,非常高效**。
|
||||
|
||||
## 堆常见应用
|
||||
|
||||
- **优先队列**。堆常作为实现优先队列的首选数据结构,入队和出队操作时间复杂度为 $O(\log n)$ ,建队操作为 $O(n)$ ,皆非常高效。
|
||||
- **堆排序**。给定一组数据,我们使用其建堆,并依次全部弹出,则可以得到有序的序列。当然,堆排序一般无需弹出元素,仅需每轮将堆顶元素交换至数组尾部并减小堆的长度即可。
|
||||
- **获取最大的 $k$ 个元素**。这既是一道经典算法题目,也是一种常见应用,例如选取热度前 10 的新闻作为微博热搜,选取前 10 销量的商品等。
|
@ -41,4 +41,26 @@ comments: true
|
||||
|
||||
非常欢迎您和我一同来创作本书!
|
||||
|
||||
## 离线部署
|
||||
|
||||
### Docker
|
||||
|
||||
使用本教程前,请确保 Docker 已经安装并启动。
|
||||
|
||||
根据如下命令离线部署。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/krahets/hello-algo.git
|
||||
cd hello-algo
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
稍等片刻,即可通过浏览器打开 `http://localhost:8000` 访问本教程。
|
||||
|
||||
使用如下命令删除部署。
|
||||
|
||||
```bash
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
(TODO:教学视频)
|
||||
|
@ -170,7 +170,7 @@ comments: true
|
||||
|
||||
```c title="bubble_sort.c"
|
||||
/* 冒泡排序 */
|
||||
void bubble_sort(int nums[], int size) {
|
||||
void bubbleSort(int nums[], int size) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (int i = 0; i < size - 1; i++)
|
||||
{
|
||||
@ -373,7 +373,7 @@ comments: true
|
||||
|
||||
```c title="bubble_sort.c"
|
||||
/* 冒泡排序 */
|
||||
void bubble_sort(int nums[], int size) {
|
||||
void bubbleSortWithFlag(int nums[], int size) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (int i = 0; i < size - 1; i++)
|
||||
{
|
||||
|
@ -18,16 +18,16 @@ comments: true
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| 方法 | 描述 |
|
||||
| ------------ | ---------------- |
|
||||
| offerFirst() | 将元素添加至队首 |
|
||||
| offerLast() | 将元素添加至队尾 |
|
||||
| pollFirst() | 删除队首元素 |
|
||||
| pollLast() | 删除队尾元素 |
|
||||
| peekFirst() | 访问队首元素 |
|
||||
| peekLast() | 访问队尾元素 |
|
||||
| size() | 获取队列的长度 |
|
||||
| isEmpty() | 判断队列是否为空 |
|
||||
| 方法 | 描述 | 时间复杂度 |
|
||||
| ------------ | ---------------- | ---------- |
|
||||
| offerFirst() | 将元素添加至队首 | $O(1)$ |
|
||||
| offerLast() | 将元素添加至队尾 | $O(1)$ |
|
||||
| pollFirst() | 删除队首元素 | $O(1)$ |
|
||||
| pollLast() | 删除队尾元素 | $O(1)$ |
|
||||
| peekFirst() | 访问队首元素 | $O(1)$ |
|
||||
| peekLast() | 访问队尾元素 | $O(1)$ |
|
||||
| size() | 获取队列的长度 | $O(1)$ |
|
||||
| isEmpty() | 判断队列是否为空 | $O(1)$ |
|
||||
|
||||
</div>
|
||||
|
||||
@ -196,5 +196,5 @@ comments: true
|
||||
=== "Swift"
|
||||
|
||||
```swift title="deque.swift"
|
||||
|
||||
|
||||
```
|
||||
|
@ -20,13 +20,13 @@ comments: true
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| 方法 | 描述 |
|
||||
| --------- | ---------------------------- |
|
||||
| offer() | 元素入队,即将元素添加至队尾 |
|
||||
| poll() | 队首元素出队 |
|
||||
| front() | 访问队首元素 |
|
||||
| size() | 获取队列的长度 |
|
||||
| isEmpty() | 判断队列是否为空 |
|
||||
| 方法 | 描述 | 时间复杂度 |
|
||||
| --------- | ---------------------------- | ---------- |
|
||||
| offer() | 元素入队,即将元素添加至队尾 | $O(1)$ |
|
||||
| poll() | 队首元素出队 | $O(1)$ |
|
||||
| front() | 访问队首元素 | $O(1)$ |
|
||||
| size() | 获取队列的长度 | $O(1)$ |
|
||||
| isEmpty() | 判断队列是否为空 | $O(1)$ |
|
||||
|
||||
</div>
|
||||
|
||||
|
@ -22,13 +22,13 @@ comments: true
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| 方法 | 描述 |
|
||||
| --------- | ---------------------- |
|
||||
| push() | 元素入栈(添加至栈顶) |
|
||||
| pop() | 栈顶元素出栈 |
|
||||
| peek() | 访问栈顶元素 |
|
||||
| size() | 获取栈的长度 |
|
||||
| isEmpty() | 判断栈是否为空 |
|
||||
| 方法 | 描述 | 时间复杂度 |
|
||||
| --------- | ---------------------- | ---------- |
|
||||
| push() | 元素入栈(添加至栈顶) | $O(1)$ |
|
||||
| pop() | 栈顶元素出栈 | $O(1)$ |
|
||||
| peek() | 访问栈顶元素 | $O(1)$ |
|
||||
| size() | 获取栈的长度 | $O(1)$ |
|
||||
| isEmpty() | 判断栈是否为空 | $O(1)$ |
|
||||
|
||||
</div>
|
||||
|
||||
|
@ -114,7 +114,7 @@ comments: true
|
||||
|
||||
结点的两个指针分别指向「左子结点 Left Child Node」和「右子结点 Right Child Node」,并且称该结点为两个子结点的「父结点 Parent Node」。给定二叉树某结点,将左子结点以下的树称为该结点的「左子树 Left Subtree」,右子树同理。
|
||||
|
||||
除了叶结点外,每个结点都有子结点和子树。例如,若将上图的「结点 2」看作父结点,那么其左子结点和右子结点分别为「结点 4」和「结点 5」,左子树和右子树分别为「结点 4 及其以下结点形成的树」和「结点 5 及其以下结点形成的树」。
|
||||
除了叶结点外,每个结点都有子结点和子树。例如,若将下图的「结点 2」看作父结点,那么其左子结点和右子结点分别为「结点 4」和「结点 5」,左子树和右子树分别为「结点 4 及其以下结点形成的树」和「结点 5 及其以下结点形成的树」。
|
||||
|
||||

|
||||
|
||||
|
@ -15,4 +15,4 @@ comments: true
|
||||
- 前序、中序、后序遍历是深度优先搜索,体现着“走到头、再回头继续”的回溯遍历方式,通常使用递归实现。
|
||||
- 二叉搜索树是一种高效的元素查找数据结构,查找、插入、删除操作的时间复杂度皆为 $O(\log n)$ 。二叉搜索树退化为链表后,各项时间复杂度劣化至 $O(n)$ ,因此如何避免退化是非常重要的课题。
|
||||
- AVL 树又称平衡二叉搜索树,其通过旋转操作,使得在不断插入与删除结点后,仍然可以保持二叉树的平衡(不退化)。
|
||||
- AVL 树的旋转操作分为右旋、左旋、先右旋后左旋、先左旋后右旋。在插入或删除结点后,AVL 树会从底置顶地执行旋转操作,使树恢复平衡。
|
||||
- AVL 树的旋转操作分为右旋、左旋、先右旋后左旋、先左旋后右旋。在插入或删除结点后,AVL 树会从底至顶地执行旋转操作,使树恢复平衡。
|
||||
|
@ -161,6 +161,8 @@ nav:
|
||||
- 二叉搜索树: chapter_tree/binary_search_tree.md
|
||||
- AVL 树 *: chapter_tree/avl_tree.md
|
||||
- 小结: chapter_tree/summary.md
|
||||
- 堆:
|
||||
- 堆(Heap): chapter_heap/heap.md
|
||||
- 查找算法:
|
||||
- 线性查找: chapter_searching/linear_search.md
|
||||
- 二分查找: chapter_searching/binary_search.md
|
||||
|