diff --git a/README.md b/README.md index 143c33cb06..ff2ff96e67 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,20 @@

-

+

《 Hello,算法 》 -

+

动画图解、能运行、可讨论的
数据结构与算法快速入门教程

+
+ +

+ +

+

前往阅读 > @@ -21,21 +27,21 @@

---- - -## 关于本书 +### 关于本书 本书是我利用业余时间创作,完全开源免费,不会收取任何费用。 -本书定期更新中,希望您可以一同参与到本书的创作中来,详情见 [一起参与创作](https://www.hello-algo.com/chapter_introduction/contribution/) 。 +本书定期更新中,希望您可以一同参与到本书的创作中来,详情见 [一起参与创作](https://www.hello-algo.com/chapter_preface/contribution/) 。 - 如果发现笔误、无效链接、内容缺失、文字歧义、解释不清晰、行文结构不合理等问题,烦请您帮忙修正内容,以帮助其他读者获取更优质的学习内容。 -- 非常欢迎您和我一同来创作本书,包括重写某章节、新增章节、翻译代码至其他编程语言等,如果有意请与我联系 WeChat: krahets-jyd , Email: krahets@163.com 。 +- 非常欢迎您和我一同来创作本书,包括重写某章节、新增章节等,如果有意请与我联系 WeChat: krahets-jyd , Email: krahets@163.com 。 如果感觉本书对你有所帮助,请点个 Star 支持一下,谢谢! -## License +### 致谢 -![cc_by-nc-sa](https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png) +感谢本开源书的每一位撰稿人,是他们的无私奉献让这本书变得更好,他们的 GitHub ID(按首次提交时间排序)为:krahets, *(等待下一位创作者)* + +## License The **texts, codes, images, photos, and videos** present on this work is licensed under [CC BY-NC-SA-4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/). diff --git a/codes/cpp/chapter_array_and_linkedlist/array.cpp b/codes/cpp/chapter_array_and_linkedlist/array.cpp new file mode 100644 index 0000000000..d52e9d979e --- /dev/null +++ b/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -0,0 +1,6 @@ +/* + * File: array.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp b/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp new file mode 100644 index 0000000000..0ef70fcc46 --- /dev/null +++ b/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp @@ -0,0 +1,6 @@ +/* + * File: linked_list.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_array_and_linkedlist/list.cpp b/codes/cpp/chapter_array_and_linkedlist/list.cpp new file mode 100644 index 0000000000..08b72d58bc --- /dev/null +++ b/codes/cpp/chapter_array_and_linkedlist/list.cpp @@ -0,0 +1,6 @@ +/* + * File: list.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_array_and_linkedlist/my_list.cpp b/codes/cpp/chapter_array_and_linkedlist/my_list.cpp new file mode 100644 index 0000000000..66d4078c08 --- /dev/null +++ b/codes/cpp/chapter_array_and_linkedlist/my_list.cpp @@ -0,0 +1,6 @@ +/* + * File: my_list.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_computational_complexity/leetcode_two_sum.cpp b/codes/cpp/chapter_computational_complexity/leetcode_two_sum.cpp new file mode 100644 index 0000000000..c8f10039f1 --- /dev/null +++ b/codes/cpp/chapter_computational_complexity/leetcode_two_sum.cpp @@ -0,0 +1,6 @@ +/* + * File: leetcode_two_sum.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_computational_complexity/space_complexity_types.cpp b/codes/cpp/chapter_computational_complexity/space_complexity_types.cpp new file mode 100644 index 0000000000..78abdb7ce1 --- /dev/null +++ b/codes/cpp/chapter_computational_complexity/space_complexity_types.cpp @@ -0,0 +1,6 @@ +/* + * File: space_complexity_types.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_computational_complexity/time_complexity_types.cpp b/codes/cpp/chapter_computational_complexity/time_complexity_types.cpp new file mode 100644 index 0000000000..d913f7762c --- /dev/null +++ b/codes/cpp/chapter_computational_complexity/time_complexity_types.cpp @@ -0,0 +1,6 @@ +/* + * File: time_complexity_types.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_computational_complexity/worst_best_time_complexity.cpp b/codes/cpp/chapter_computational_complexity/worst_best_time_complexity.cpp new file mode 100644 index 0000000000..9367e12377 --- /dev/null +++ b/codes/cpp/chapter_computational_complexity/worst_best_time_complexity.cpp @@ -0,0 +1,6 @@ +/* + * File: worst_best_time_complexity.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_searching/binary_search.cpp b/codes/cpp/chapter_searching/binary_search.cpp new file mode 100644 index 0000000000..7ce1040403 --- /dev/null +++ b/codes/cpp/chapter_searching/binary_search.cpp @@ -0,0 +1,6 @@ +/* + * File: binary_search.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_searching/hashing_search.cpp b/codes/cpp/chapter_searching/hashing_search.cpp new file mode 100644 index 0000000000..8c2eafbac3 --- /dev/null +++ b/codes/cpp/chapter_searching/hashing_search.cpp @@ -0,0 +1,6 @@ +/* + * File: hashing_search.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_searching/linear_search.cpp b/codes/cpp/chapter_searching/linear_search.cpp new file mode 100644 index 0000000000..451a13fc49 --- /dev/null +++ b/codes/cpp/chapter_searching/linear_search.cpp @@ -0,0 +1,6 @@ +/* + * File: linear_search.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_sorting/bubble_sort.cpp b/codes/cpp/chapter_sorting/bubble_sort.cpp new file mode 100644 index 0000000000..3afc0203ea --- /dev/null +++ b/codes/cpp/chapter_sorting/bubble_sort.cpp @@ -0,0 +1,6 @@ +/* + * File: bubble_sort.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_sorting/insertion_sort.cpp b/codes/cpp/chapter_sorting/insertion_sort.cpp new file mode 100644 index 0000000000..bac8866119 --- /dev/null +++ b/codes/cpp/chapter_sorting/insertion_sort.cpp @@ -0,0 +1,6 @@ +/* + * File: insertion_sort.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_sorting/merge_sort.cpp b/codes/cpp/chapter_sorting/merge_sort.cpp new file mode 100644 index 0000000000..9120b38fdc --- /dev/null +++ b/codes/cpp/chapter_sorting/merge_sort.cpp @@ -0,0 +1,6 @@ +/* + * File: merge_sort.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_sorting/quick_sort.cpp b/codes/cpp/chapter_sorting/quick_sort.cpp new file mode 100644 index 0000000000..fb196acf2b --- /dev/null +++ b/codes/cpp/chapter_sorting/quick_sort.cpp @@ -0,0 +1,6 @@ +/* + * File: quick_sort.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/array_queue.cpp b/codes/cpp/chapter_stack_and_queue/array_queue.cpp new file mode 100644 index 0000000000..6df107f1f0 --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/array_queue.cpp @@ -0,0 +1,6 @@ +/* + * File: array_queue.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/array_stack.cpp b/codes/cpp/chapter_stack_and_queue/array_stack.cpp new file mode 100644 index 0000000000..fda446f204 --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/array_stack.cpp @@ -0,0 +1,6 @@ +/* + * File: array_stack.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/deque.cpp b/codes/cpp/chapter_stack_and_queue/deque.cpp new file mode 100644 index 0000000000..b48602e323 --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/deque.cpp @@ -0,0 +1,6 @@ +/* + * File: deque.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp b/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp new file mode 100644 index 0000000000..b8508cdfeb --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp @@ -0,0 +1,6 @@ +/* + * File: linkedlist_queue.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/linkedlist_stack.cpp b/codes/cpp/chapter_stack_and_queue/linkedlist_stack.cpp new file mode 100644 index 0000000000..c3334b669a --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/linkedlist_stack.cpp @@ -0,0 +1,6 @@ +/* + * File: linkedlist_stack.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/queue.cpp b/codes/cpp/chapter_stack_and_queue/queue.cpp new file mode 100644 index 0000000000..9f31c579b4 --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/queue.cpp @@ -0,0 +1,6 @@ +/* + * File: queue.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_stack_and_queue/stack.cpp b/codes/cpp/chapter_stack_and_queue/stack.cpp new file mode 100644 index 0000000000..0504e7b9d2 --- /dev/null +++ b/codes/cpp/chapter_stack_and_queue/stack.cpp @@ -0,0 +1,6 @@ +/* + * File: stack.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_tree/binary_search_tree.cpp b/codes/cpp/chapter_tree/binary_search_tree.cpp new file mode 100644 index 0000000000..243b68f8bc --- /dev/null +++ b/codes/cpp/chapter_tree/binary_search_tree.cpp @@ -0,0 +1,6 @@ +/* + * File: binary_search_tree.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_tree/binary_tree.cpp b/codes/cpp/chapter_tree/binary_tree.cpp new file mode 100644 index 0000000000..f22a04bad6 --- /dev/null +++ b/codes/cpp/chapter_tree/binary_tree.cpp @@ -0,0 +1,6 @@ +/* + * File: binary_tree.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_tree/binary_tree_bfs.cpp b/codes/cpp/chapter_tree/binary_tree_bfs.cpp new file mode 100644 index 0000000000..5ecc7bd587 --- /dev/null +++ b/codes/cpp/chapter_tree/binary_tree_bfs.cpp @@ -0,0 +1,6 @@ +/* + * File: binary_tree_bfs.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/chapter_tree/binary_tree_dfs.cpp b/codes/cpp/chapter_tree/binary_tree_dfs.cpp new file mode 100644 index 0000000000..442de6e5a4 --- /dev/null +++ b/codes/cpp/chapter_tree/binary_tree_dfs.cpp @@ -0,0 +1,6 @@ +/* + * File: binary_tree_dfs.cpp + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + diff --git a/codes/cpp/include/ListNode.hpp b/codes/cpp/include/ListNode.hpp new file mode 100644 index 0000000000..41916499e4 --- /dev/null +++ b/codes/cpp/include/ListNode.hpp @@ -0,0 +1,50 @@ +/* + * File: PrintUtil.hpp + * Created Time: 2021-12-19 + * Author: Krahets (krahets@163.com) + */ + +#pragma once + +#include +using namespace std; + +/** + * @brief Definition for a singly-linked list node + * + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(nullptr) {} +}; + +/** + * @brief Generate a linked list with a vector + * + * @param list + * @return ListNode* + */ +ListNode* vectorToLinkedList(vector list) { + ListNode *dum = new ListNode(0); + ListNode *head = dum; + for (int val : list) { + head->next = new ListNode(val); + head = head->next; + } + return dum->next; +} + +/** + * @brief Get a list node with specific value from a linked list + * + * @param head + * @param val + * @return ListNode* + */ +ListNode* getListNode(ListNode *head, int val) { + while (head != nullptr && head->val != val) { + head = head->next; + } + return head; +} diff --git a/codes/cpp/include/PrintUtil.hpp b/codes/cpp/include/PrintUtil.hpp new file mode 100644 index 0000000000..34e8b86870 --- /dev/null +++ b/codes/cpp/include/PrintUtil.hpp @@ -0,0 +1,197 @@ +/* + * File: PrintUtil.hpp + * Created Time: 2021-12-19 + * Author: Krahets (krahets@163.com) + */ + +#pragma once + +#include +#include +#include +#include "ListNode.hpp" +#include "TreeNode.hpp" + +class PrintUtil { + public: + /** + * @brief Find an element in a vector + * + * @tparam T + * @param vec + * @param ele + * @return int + */ + template + static int vecFind(const vector& vec, T ele) { + int j = INT_MAX; + for (int i = 0; i < vec.size(); i++) { + if (vec[i] == ele) { + j = i; + } + } + return j; + } + + /** + * @brief Concatenate a vector with a delim + * + * @tparam T + * @param delim + * @param vec + * @return string + */ + template + static string strJoin(const string& delim, const T& vec) { + ostringstream s; + for (const auto& i : vec) { + if (&i != &vec[0]) { + s << delim; + } + s << i; + } + return s.str(); + } + + /** + * @brief Repeat a string for n times + * + * @param str + * @param n + * @return string + */ + static string strRepeat(string str, int n) { + ostringstream os; + for(int i = 0; i < n; i++) + os << str; + return os.str(); + } + + /** + * @brief Get the Vector String object + * + * @tparam T + * @param list + * @return string + */ + template + static string getVectorString(vector &list) { + return "[" + strJoin(", ", list) + "]"; + } + + /** + * @brief Print a vector + * + * @tparam T + * @param list + */ + template + static void printVector(vector &list) { + cout << getVectorString(list) << '\n'; + } + + /** + * @brief Print a vector matrix + * + * @tparam T + * @param matrix + */ + template + static void printVectorMatrix(vector> &matrix) { + cout << "[" << '\n'; + for (vector &list : matrix) + cout << " " + getVectorString(list) + "," << '\n'; + cout << "]" << '\n'; + } + + /** + * @brief Print a linked list + * + * @param head + */ + static void printLinkedList(ListNode *head) { + vector list; + while (head != nullptr) { + list.push_back(head->val); + head = head->next; + } + + cout << strJoin(" -> ", list) << '\n'; + } + + /** + * @brief This tree printer is borrowed from TECHIE DELIGHT + * https://www.techiedelight.com/c-program-print-binary-tree/ + */ + struct Trunk { + Trunk *prev; + string str; + Trunk(Trunk *prev, string str) { + this->prev = prev; + this->str = str; + } + }; + + /** + * @brief Helper function to print branches of the binary tree + * + * @param p + */ + static void showTrunks(Trunk *p) { + if (p == nullptr) { + return; + } + + showTrunks(p->prev); + cout << p->str; + } + + /** + * @brief The interface of the tree printer + * + * @param root + */ + static void printTree(TreeNode *root) { + printTree(root, nullptr, false); + } + + /** + * @brief Print a binary tree + * + * @param root + * @param prev + * @param isLeft + */ + static void printTree(TreeNode *root, Trunk *prev, bool isLeft) { + if (root == nullptr) { + return; + } + + string prev_str = " "; + Trunk *trunk = new Trunk(prev, prev_str); + + printTree(root->right, trunk, true); + + if (!prev) { + trunk->str = "———"; + } + else if (isLeft) { + trunk->str = "/———"; + prev_str = " |"; + } + else { + trunk->str = "\\———"; + prev->str = prev_str; + } + + showTrunks(trunk); + cout << " " << root->val << endl; + + if (prev) { + prev->str = prev_str; + } + trunk->str = " |"; + + printTree(root->left, trunk, false); + } +}; diff --git a/codes/cpp/include/TreeNode.hpp b/codes/cpp/include/TreeNode.hpp new file mode 100644 index 0000000000..a8e9d0466b --- /dev/null +++ b/codes/cpp/include/TreeNode.hpp @@ -0,0 +1,63 @@ +/* + * File: PrintUtil.hpp + * Created Time: 2021-12-19 + * Author: Krahets (krahets@163.com) + */ + +#pragma once + +/** + * @brief Definition for a binary tree node + * + */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +/** + * @brief Generate a binary tree with a vector + * + * @param list + * @return TreeNode* + */ +TreeNode* vectorToTree(vector list) { + TreeNode *root = new TreeNode(list[0]); + queue que; + que.emplace(root); + int i = 1; + while(!que.empty()) { + TreeNode *node = que.front(); + que.pop(); + if(list[i] != INT_MAX) { + node->left = new TreeNode(list[i]); + que.emplace(node->left); + } + i++; + if(list[i] != INT_MAX) { + node->right = new TreeNode(list[i]); + que.emplace(node->right); + } + i++; + } + return root; +} + +/** + * @brief Get a tree node with specific value in a binary tree + * + * @param root + * @param val + * @return TreeNode* + */ +TreeNode* getTreeNode(TreeNode *root, int val) { + if (root == nullptr) + return nullptr; + if (root->val == val) + return root; + TreeNode *left = getTreeNode(root->left, val); + TreeNode *right = getTreeNode(root->right, val); + return left != nullptr ? left : right; +} diff --git a/codes/cpp/include/include.hpp b/codes/cpp/include/include.hpp new file mode 100644 index 0000000000..8e84583fba --- /dev/null +++ b/codes/cpp/include/include.hpp @@ -0,0 +1,23 @@ +/* + * File: PrintUtil.hpp + * Created Time: 2021-12-19 + * Author: Krahets (krahets@163.com) + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ListNode.hpp" +#include "TreeNode.hpp" +#include "PrintUtil.hpp" + +using namespace std; diff --git a/codes/java/chapter_array_and_linkedlist/array.java b/codes/java/chapter_array_and_linkedlist/array.java index 1a1c673ba8..76b436dc1c 100644 --- a/codes/java/chapter_array_and_linkedlist/array.java +++ b/codes/java/chapter_array_and_linkedlist/array.java @@ -1,3 +1,9 @@ +/* + * File: array.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_array_and_linkedlist; import java.util.*; diff --git a/codes/java/chapter_array_and_linkedlist/linked_list.java b/codes/java/chapter_array_and_linkedlist/linked_list.java index 9a1dedbc59..3d44511789 100644 --- a/codes/java/chapter_array_and_linkedlist/linked_list.java +++ b/codes/java/chapter_array_and_linkedlist/linked_list.java @@ -1,3 +1,9 @@ +/* + * File: linked_list.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_array_and_linkedlist; import include.*; diff --git a/codes/java/chapter_array_and_linkedlist/list.java b/codes/java/chapter_array_and_linkedlist/list.java index 94391f1752..1f13bc2efd 100644 --- a/codes/java/chapter_array_and_linkedlist/list.java +++ b/codes/java/chapter_array_and_linkedlist/list.java @@ -1,3 +1,9 @@ +/* + * File: list.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_array_and_linkedlist; import java.util.*; diff --git a/codes/java/chapter_array_and_linkedlist/my_list.java b/codes/java/chapter_array_and_linkedlist/my_list.java index 67b255410a..d4db0a2c3c 100644 --- a/codes/java/chapter_array_and_linkedlist/my_list.java +++ b/codes/java/chapter_array_and_linkedlist/my_list.java @@ -1,3 +1,9 @@ +/* + * File: my_list.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_array_and_linkedlist; import java.util.*; @@ -14,12 +20,12 @@ public MyList() { nums = new int[initialCapacity]; } - /* 获取列表容量 */ + /* 获取列表长度(即当前元素数量)*/ public int size() { return size; } - /* 获取列表长度(即当前元素数量) */ + /* 获取列表容量 */ public int capacity() { return nums.length; } diff --git a/codes/java/chapter_computational_complexity/leetcode_two_sum.java b/codes/java/chapter_computational_complexity/leetcode_two_sum.java index 447fc66567..328e1c294e 100644 --- a/codes/java/chapter_computational_complexity/leetcode_two_sum.java +++ b/codes/java/chapter_computational_complexity/leetcode_two_sum.java @@ -1,3 +1,9 @@ +/* + * File: leetcode_two_sum.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_computational_complexity; import java.util.*; diff --git a/codes/java/chapter_computational_complexity/space_complexity_types.java b/codes/java/chapter_computational_complexity/space_complexity_types.java index 7ad3236bff..182dc47ef8 100644 --- a/codes/java/chapter_computational_complexity/space_complexity_types.java +++ b/codes/java/chapter_computational_complexity/space_complexity_types.java @@ -1,3 +1,9 @@ +/* + * File: space_complexity_types.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_computational_complexity; import include.*; diff --git a/codes/java/chapter_computational_complexity/time_complexity_types.java b/codes/java/chapter_computational_complexity/time_complexity_types.java index 4b8554446b..2237ed977c 100644 --- a/codes/java/chapter_computational_complexity/time_complexity_types.java +++ b/codes/java/chapter_computational_complexity/time_complexity_types.java @@ -1,3 +1,9 @@ +/* + * File: time_complexity_types.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_computational_complexity; public class time_complexity_types { diff --git a/codes/java/chapter_computational_complexity/worst_best_time_complexity.java b/codes/java/chapter_computational_complexity/worst_best_time_complexity.java index 8c0009d595..536bf3af0d 100644 --- a/codes/java/chapter_computational_complexity/worst_best_time_complexity.java +++ b/codes/java/chapter_computational_complexity/worst_best_time_complexity.java @@ -1,3 +1,9 @@ +/* + * File: worst_best_time_complexity.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_computational_complexity; import java.util.*; diff --git a/codes/java/chapter_searching/binary_search.java b/codes/java/chapter_searching/binary_search.java index c80db3c9b0..cb5bd94190 100644 --- a/codes/java/chapter_searching/binary_search.java +++ b/codes/java/chapter_searching/binary_search.java @@ -1,3 +1,9 @@ +/* + * File: binary_search.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_searching; public class binary_search { diff --git a/codes/java/chapter_searching/hashing_search.java b/codes/java/chapter_searching/hashing_search.java index 51f396eaad..fa58baa464 100644 --- a/codes/java/chapter_searching/hashing_search.java +++ b/codes/java/chapter_searching/hashing_search.java @@ -1,3 +1,9 @@ +/* + * File: hashing_search.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_searching; import include.*; diff --git a/codes/java/chapter_searching/linear_search.java b/codes/java/chapter_searching/linear_search.java index 7a68003c52..269aa07da1 100644 --- a/codes/java/chapter_searching/linear_search.java +++ b/codes/java/chapter_searching/linear_search.java @@ -1,3 +1,9 @@ +/* + * File: linear_search.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_searching; import include.*; diff --git a/codes/java/chapter_sorting/bubble_sort.java b/codes/java/chapter_sorting/bubble_sort.java index e5ffb1b6c5..eb30a9acbb 100644 --- a/codes/java/chapter_sorting/bubble_sort.java +++ b/codes/java/chapter_sorting/bubble_sort.java @@ -1,3 +1,9 @@ +/* + * File: bubble_sort.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_sorting; import java.util.*; diff --git a/codes/java/chapter_sorting/insertion_sort.java b/codes/java/chapter_sorting/insertion_sort.java index 2e8d26d32f..511f4bfeab 100644 --- a/codes/java/chapter_sorting/insertion_sort.java +++ b/codes/java/chapter_sorting/insertion_sort.java @@ -1,3 +1,9 @@ +/* + * File: insertion_sort.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_sorting; import java.util.*; diff --git a/codes/java/chapter_sorting/merge_sort.java b/codes/java/chapter_sorting/merge_sort.java index cc93435968..a948ebd535 100644 --- a/codes/java/chapter_sorting/merge_sort.java +++ b/codes/java/chapter_sorting/merge_sort.java @@ -1,3 +1,9 @@ +/* + * File: merge_sort.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_sorting; import java.util.*; diff --git a/codes/java/chapter_sorting/quick_sort.java b/codes/java/chapter_sorting/quick_sort.java index a9961912ad..d65aa8e4bd 100644 --- a/codes/java/chapter_sorting/quick_sort.java +++ b/codes/java/chapter_sorting/quick_sort.java @@ -1,3 +1,9 @@ +/* + * File: quick_sort.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_sorting; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/array_queue.java b/codes/java/chapter_stack_and_queue/array_queue.java index 1f25c99951..251e7ac4ad 100644 --- a/codes/java/chapter_stack_and_queue/array_queue.java +++ b/codes/java/chapter_stack_and_queue/array_queue.java @@ -1,3 +1,9 @@ +/* + * File: array_queue.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/array_stack.java b/codes/java/chapter_stack_and_queue/array_stack.java index 5f2b74081b..395e79efe8 100644 --- a/codes/java/chapter_stack_and_queue/array_stack.java +++ b/codes/java/chapter_stack_and_queue/array_stack.java @@ -1,3 +1,9 @@ +/* + * File: array_stack.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/deque.java b/codes/java/chapter_stack_and_queue/deque.java index 837eb90a5d..095e528336 100644 --- a/codes/java/chapter_stack_and_queue/deque.java +++ b/codes/java/chapter_stack_and_queue/deque.java @@ -1,3 +1,9 @@ +/* + * File: deque.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/linkedlist_queue.java b/codes/java/chapter_stack_and_queue/linkedlist_queue.java index 22224c8463..30ddeb170f 100644 --- a/codes/java/chapter_stack_and_queue/linkedlist_queue.java +++ b/codes/java/chapter_stack_and_queue/linkedlist_queue.java @@ -1,3 +1,9 @@ +/* + * File: linkedlist_queue.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/linkedlist_stack.java b/codes/java/chapter_stack_and_queue/linkedlist_stack.java index bf626f6f86..003977b026 100644 --- a/codes/java/chapter_stack_and_queue/linkedlist_stack.java +++ b/codes/java/chapter_stack_and_queue/linkedlist_stack.java @@ -1,3 +1,9 @@ +/* + * File: linkedlist_stack.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/queue.java b/codes/java/chapter_stack_and_queue/queue.java index fecf2b2cda..4d22b50289 100644 --- a/codes/java/chapter_stack_and_queue/queue.java +++ b/codes/java/chapter_stack_and_queue/queue.java @@ -1,3 +1,9 @@ +/* + * File: queue.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_stack_and_queue/stack.java b/codes/java/chapter_stack_and_queue/stack.java index f6add4d127..1ae525c387 100644 --- a/codes/java/chapter_stack_and_queue/stack.java +++ b/codes/java/chapter_stack_and_queue/stack.java @@ -1,3 +1,9 @@ +/* + * File: stack.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_stack_and_queue; import java.util.*; diff --git a/codes/java/chapter_tree/binary_search_tree.java b/codes/java/chapter_tree/binary_search_tree.java index d338937466..f39f3d1c7d 100644 --- a/codes/java/chapter_tree/binary_search_tree.java +++ b/codes/java/chapter_tree/binary_search_tree.java @@ -1,3 +1,9 @@ +/* + * File: binary_search_tree.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_tree; import java.util.*; diff --git a/codes/java/chapter_tree/binary_tree.java b/codes/java/chapter_tree/binary_tree.java index 76d6059c87..8f25a9a16b 100644 --- a/codes/java/chapter_tree/binary_tree.java +++ b/codes/java/chapter_tree/binary_tree.java @@ -1,3 +1,9 @@ +/* + * File: binary_tree.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_tree; import include.*; diff --git a/codes/java/chapter_tree/binary_tree_bfs.java b/codes/java/chapter_tree/binary_tree_bfs.java index f196937a5e..524274a684 100644 --- a/codes/java/chapter_tree/binary_tree_bfs.java +++ b/codes/java/chapter_tree/binary_tree_bfs.java @@ -1,3 +1,9 @@ +/* + * File: binary_tree_bfs.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_tree; import include.*; diff --git a/codes/java/chapter_tree/binary_tree_dfs.java b/codes/java/chapter_tree/binary_tree_dfs.java index 15e12216e0..fa866d9656 100644 --- a/codes/java/chapter_tree/binary_tree_dfs.java +++ b/codes/java/chapter_tree/binary_tree_dfs.java @@ -1,3 +1,9 @@ +/* + * File: binary_tree_dfs.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package chapter_tree; import include.*; diff --git a/codes/java/include/ListNode.java b/codes/java/include/ListNode.java index c8a2283a9e..14308feb42 100755 --- a/codes/java/include/ListNode.java +++ b/codes/java/include/ListNode.java @@ -1,3 +1,9 @@ +/* + * File: ListNode.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package include; /** diff --git a/codes/java/include/PrintUtil.java b/codes/java/include/PrintUtil.java index ea715910a7..e6e718ceae 100755 --- a/codes/java/include/PrintUtil.java +++ b/codes/java/include/PrintUtil.java @@ -1,3 +1,9 @@ +/* + * File: PrintUtil.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package include; import java.util.*; diff --git a/codes/java/include/TreeNode.java b/codes/java/include/TreeNode.java index e7daebb023..bba76b1234 100755 --- a/codes/java/include/TreeNode.java +++ b/codes/java/include/TreeNode.java @@ -1,3 +1,9 @@ +/* + * File: TreeNode.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + package include; import java.util.*; diff --git a/codes/python/chapter_array_and_linkedlist/array.py b/codes/python/chapter_array_and_linkedlist/array.py new file mode 100644 index 0000000000..f505aa43e6 --- /dev/null +++ b/codes/python/chapter_array_and_linkedlist/array.py @@ -0,0 +1,89 @@ +''' +File: array.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + +""" 随机访问元素 """ +def randomAccess(nums): + # 在区间 [0, len(nums)) 中随机抽取一个数字 + random_index = random.randint(0, len(nums)) + # 获取并返回随机元素 + random_num = nums[random_index] + return random_num + +""" 扩展数组长度 """ +def extend(nums, enlarge): + # 初始化一个扩展长度后的数组 + res = [0] * (len(nums) + enlarge) + # 将原数组中的所有元素复制到新数组 + for i in range(len(nums)): + res[i] = nums[i] + # 返回扩展后的新数组 + return res + +""" 在数组的索引 index 处插入元素 num """ +def insert(nums, num, index): + # 把索引 index 以及之后的所有元素向后移动一位 + for i in range(len(nums) - 1, index - 1, -1): + nums[i] = nums[i - 1] + # 将 num 赋给 index 处元素 + nums[index] = num + +""" 删除索引 index 处元素 """ +def remove(nums, index): + # 把索引 index 之后的所有元素向前移动一位 + for i in range(index, len(nums) - 1): + nums[i] = nums[i + 1] + +""" 遍历数组 """ +def traverse(nums): + count = 0 + # 通过索引遍历数组 + for i in range(len(nums)): + count += 1 + # 直接遍历数组 + for num in nums: + count += 1 + +""" 在数组中查找指定元素 """ +def find(nums, target): + for i in range(len(nums)): + if nums[i] == target: + return i + return -1 + +""" Driver Code """ +if __name__ == "__main__": + """ 初始化数组 """ + arr = [0] * 5 + print("数组 arr =", arr) + nums = [1, 3, 2, 5, 4] + print("数组 nums =", nums) + + """ 随机访问 """ + random_num = randomAccess(nums) + print("在 nums 中获取随机元素", random_num) + + """ 长度扩展 """ + nums = extend(nums, 3) + print("将数组长度扩展至 8 ,得到 nums =", nums) + + """ 插入元素 """ + insert(nums, 6, 3) + print("在索引 3 处插入数字 6 ,得到 nums =", nums) + + """ 删除元素 """ + remove(nums, 2) + print("删除索引 2 处的元素,得到 nums =", nums) + + """ 遍历数组 """ + traverse(nums) + + """ 查找元素 """ + index = find(nums, 3) + print("在 nums 中查找元素 3 ,得到索引 =", index) diff --git a/codes/python/chapter_array_and_linkedlist/linked_list.py b/codes/python/chapter_array_and_linkedlist/linked_list.py new file mode 100644 index 0000000000..1f5aaca321 --- /dev/null +++ b/codes/python/chapter_array_and_linkedlist/linked_list.py @@ -0,0 +1,79 @@ +''' +File: linked_list.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + +""" 在链表的结点 n0 之后插入结点 P """ +def insert(n0, P): + n1 = n0.next + n0.next = P + P.next = n1 + +""" 删除链表的结点 n0 之后的首个结点 """ +def remove(n0): + if not n0.next: + return + # n0 -> P -> n1 + P = n0.next + n1 = P.next + n0.next = n1 + +""" 访问链表中索引为 index 的结点 """ +def access(head, index): + for _ in range(index): + head = head.next + if not head: + return None + return head + +""" 在链表中查找值为 target 的首个结点 """ +def find(head, target): + index = 0 + while head: + if head.val == target: + return index + head = head.next + index += 1 + return -1 + +""" +Driver Code +""" +if __name__ == "__main__": + """ 初始化链表 """ + # 初始化各个结点 + n0 = ListNode(1) + n1 = ListNode(3) + n2 = ListNode(2) + n3 = ListNode(5) + n4 = ListNode(4) + # 构建引用指向 + n0.next = n1 + n1.next = n2 + n2.next = n3 + n3.next = n4 + print("初始化的链表为") + print_linked_list(n0) + + """ 插入结点 """ + insert(n0, ListNode(0)) + print("插入结点后的链表为") + print_linked_list(n0) + + """ 删除结点 """ + remove(n0) + print("删除结点后的链表为") + print_linked_list(n0) + + """ 访问结点 """ + node = access(n0, 3) + print("链表中索引 3 处的结点的值 = {}".format(node.val)) + + """ 查找结点 """ + index = find(n0, 2) + print("链表中值为 2 的结点的索引 = {}".format(index)) diff --git a/codes/python/chapter_array_and_linkedlist/list.py b/codes/python/chapter_array_and_linkedlist/list.py new file mode 100644 index 0000000000..8f457654f8 --- /dev/null +++ b/codes/python/chapter_array_and_linkedlist/list.py @@ -0,0 +1,64 @@ +''' +File: list.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + +""" +Driver Code +""" +if __name__ == "__main__": + """ 初始化列表 """ + list = [1, 3, 2, 5, 4] + print("列表 list =", list) + + """ 访问元素 """ + num = list[1] + print("访问索引 1 处的元素,得到 num =", num) + + """ 更新元素 """ + list[1] = 0 + print("将索引 1 处的元素更新为 0 ,得到 list =", list) + + """ 清空列表 """ + list.clear() + print("清空列表后 list =", list) + + """ 尾部添加元素 """ + list.append(1) + list.append(3) + list.append(2) + list.append(5) + list.append(4) + print("添加元素后 list = ", list) + + """ 中间插入元素 """ + list.insert(3, 6) + print("在索引 3 处插入数字 6 ,得到 list =", list) + + """ 删除元素 """ + list.pop(3) + print("删除索引 3 处的元素,得到 list =", list) + + """ 通过索引遍历列表 """ + count = 0 + for i in range(len(list)): + count += 1 + + """ 直接遍历列表元素 """ + count = 0 + for n in list: + count += 1 + + """ 拼接两个列表 """ + list1 = [6, 8, 7, 10, 9] + list += list1 + print("将列表 list1 拼接到 list 之后,得到 list =", list) + + """ 排序列表 """ + list.sort() + print("排序列表后 list =", list) diff --git a/codes/python/chapter_array_and_linkedlist/my_list.py b/codes/python/chapter_array_and_linkedlist/my_list.py new file mode 100644 index 0000000000..e5202ed59b --- /dev/null +++ b/codes/python/chapter_array_and_linkedlist/my_list.py @@ -0,0 +1,110 @@ +''' +File: my_list.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + + +""" 列表类简易实现 """ +class MyList: + """ 构造函数 """ + def __init__(self): + self._initial_capacity = 10 # 列表初始容量 + self._nums = [0] * self._initial_capacity # 数组(存储列表元素) + self._size = 0 # 列表长度(即当前元素数量) + self._extend_ratio = 2 # 每次列表扩容的倍数 + + """ 获取列表长度(即当前元素数量) """ + def size(self): + return self._size + + """ 获取列表容量 """ + def capacity(self): + return len(self._nums) + + """ 访问元素 """ + def get(self, index): + # 索引如果越界则抛出异常,下同 + assert index < self._size, "索引越界" + return self._nums[index] + + """ 更新元素 """ + def set(self, num, index): + assert index < self._size, "索引越界" + self._nums[index] = num + + """ 中间插入元素 """ + def add(self, num, index=-1): + assert index < self._size, "索引越界" + if index == -1: + index = self._size + # 元素数量超出容量时,触发扩容机制 + if self._size == self.capacity(): + self.extend_capacity() + # 索引 i 以及之后的元素都向后移动一位 + for j in range(self._size - 1, index - 1, -1): + self._nums[j + 1] = self._nums[j] + self._nums[index] = num + # 更新元素数量 + self._size += 1 + + """ 删除元素 """ + def remove(self, index): + assert index < self._size, "索引越界" + # 索引 i 之后的元素都向前移动一位 + for j in range(index, self._size - 1): + self._nums[j] = self._nums[j + 1] + # 更新元素数量 + self._size -= 1 + + """ 列表扩容 """ + def extend_capacity(self): + # 新建一个长度为 self._size 的数组,并将原数组拷贝到新数组 + self._nums = self._nums + [0] * self.capacity() * (self._extend_ratio - 1) + + """ 返回有效长度的列表 """ + def to_array(self): + return self._nums[:self._size] + + +""" +Driver Code +""" +if __name__ == "__main__": + """ 初始化列表 """ + list = MyList() + """ 尾部添加元素 """ + list.add(1) + list.add(3) + list.add(2) + list.add(5) + list.add(4) + print("列表 list = {} ,容量 = {} ,长度 = {}" + .format(list.to_array(), list.capacity(), list.size())) + + """ 中间插入元素 """ + list.add(num=6, index=3) + print("在索引 3 处插入数字 6 ,得到 list =", list.to_array()) + + """ 删除元素 """ + list.remove(3) + print("删除索引 3 处的元素,得到 list =", list.to_array()) + + """ 访问元素 """ + num = list.get(1) + print("访问索引 1 处的元素,得到 num =", num) + + """ 更新元素 """ + list.set(0, 1) + print("将索引 1 处的元素更新为 0 ,得到 list =", list.to_array()) + + """ 测试扩容机制 """ + for i in range(10): + # 在 i = 5 时,列表长度将超出列表容量,此时触发扩容机制 + list.add(i) + print("扩容后的列表 list = {} ,容量 = {} ,长度 = {}" + .format(list.to_array(), list.capacity(), list.size())) diff --git a/codes/python/chapter_computational_complexity/leetcode_two_sum.py b/codes/python/chapter_computational_complexity/leetcode_two_sum.py new file mode 100644 index 0000000000..f235ddb8ee --- /dev/null +++ b/codes/python/chapter_computational_complexity/leetcode_two_sum.py @@ -0,0 +1,10 @@ +''' +File: leetcode_two_sum.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_computational_complexity/space_complexity_types.py b/codes/python/chapter_computational_complexity/space_complexity_types.py new file mode 100644 index 0000000000..8905c5b20a --- /dev/null +++ b/codes/python/chapter_computational_complexity/space_complexity_types.py @@ -0,0 +1,10 @@ +''' +File: space_complexity_types.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_computational_complexity/time_complexity_types.py b/codes/python/chapter_computational_complexity/time_complexity_types.py new file mode 100644 index 0000000000..e60ae4cfda --- /dev/null +++ b/codes/python/chapter_computational_complexity/time_complexity_types.py @@ -0,0 +1,10 @@ +''' +File: time_complexity_types.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_computational_complexity/worst_best_time_complexity.py b/codes/python/chapter_computational_complexity/worst_best_time_complexity.py new file mode 100644 index 0000000000..7a4b246d83 --- /dev/null +++ b/codes/python/chapter_computational_complexity/worst_best_time_complexity.py @@ -0,0 +1,10 @@ +''' +File: worst_best_time_complexity.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_searching/binary_search.py b/codes/python/chapter_searching/binary_search.py new file mode 100644 index 0000000000..709a2b6983 --- /dev/null +++ b/codes/python/chapter_searching/binary_search.py @@ -0,0 +1,10 @@ +''' +File: binary_search.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_searching/hashing_search.py b/codes/python/chapter_searching/hashing_search.py new file mode 100644 index 0000000000..90de74f223 --- /dev/null +++ b/codes/python/chapter_searching/hashing_search.py @@ -0,0 +1,10 @@ +''' +File: hashing_search.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_searching/linear_search.py b/codes/python/chapter_searching/linear_search.py new file mode 100644 index 0000000000..961e75fb03 --- /dev/null +++ b/codes/python/chapter_searching/linear_search.py @@ -0,0 +1,10 @@ +''' +File: linear_search.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_sorting/bubble_sort.py b/codes/python/chapter_sorting/bubble_sort.py new file mode 100644 index 0000000000..2027047a66 --- /dev/null +++ b/codes/python/chapter_sorting/bubble_sort.py @@ -0,0 +1,10 @@ +''' +File: bubble_sort.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_sorting/insertion_sort.py b/codes/python/chapter_sorting/insertion_sort.py new file mode 100644 index 0000000000..28e0331e63 --- /dev/null +++ b/codes/python/chapter_sorting/insertion_sort.py @@ -0,0 +1,10 @@ +''' +File: insertion_sort.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_sorting/merge_sort.py b/codes/python/chapter_sorting/merge_sort.py new file mode 100644 index 0000000000..6f9b4a6fb7 --- /dev/null +++ b/codes/python/chapter_sorting/merge_sort.py @@ -0,0 +1,10 @@ +''' +File: merge_sort.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_sorting/quick_sort.py b/codes/python/chapter_sorting/quick_sort.py new file mode 100644 index 0000000000..a668096306 --- /dev/null +++ b/codes/python/chapter_sorting/quick_sort.py @@ -0,0 +1,10 @@ +''' +File: quick_sort.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/array_queue.py b/codes/python/chapter_stack_and_queue/array_queue.py new file mode 100644 index 0000000000..7bc6a32613 --- /dev/null +++ b/codes/python/chapter_stack_and_queue/array_queue.py @@ -0,0 +1,10 @@ +''' +File: array_queue.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/array_stack.py b/codes/python/chapter_stack_and_queue/array_stack.py new file mode 100644 index 0000000000..0853efa263 --- /dev/null +++ b/codes/python/chapter_stack_and_queue/array_stack.py @@ -0,0 +1,10 @@ +''' +File: array_stack.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/deque.py b/codes/python/chapter_stack_and_queue/deque.py new file mode 100644 index 0000000000..9894975803 --- /dev/null +++ b/codes/python/chapter_stack_and_queue/deque.py @@ -0,0 +1,10 @@ +''' +File: deque.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/linkedlist_queue.py b/codes/python/chapter_stack_and_queue/linkedlist_queue.py new file mode 100644 index 0000000000..3606c8a469 --- /dev/null +++ b/codes/python/chapter_stack_and_queue/linkedlist_queue.py @@ -0,0 +1,10 @@ +''' +File: linkedlist_queue.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/linkedlist_stack.py b/codes/python/chapter_stack_and_queue/linkedlist_stack.py new file mode 100644 index 0000000000..252b2c7279 --- /dev/null +++ b/codes/python/chapter_stack_and_queue/linkedlist_stack.py @@ -0,0 +1,10 @@ +''' +File: linkedlist_stack.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/queue.py b/codes/python/chapter_stack_and_queue/queue.py new file mode 100644 index 0000000000..52855b2a0a --- /dev/null +++ b/codes/python/chapter_stack_and_queue/queue.py @@ -0,0 +1,10 @@ +''' +File: queue.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_stack_and_queue/stack.py b/codes/python/chapter_stack_and_queue/stack.py new file mode 100644 index 0000000000..3341600880 --- /dev/null +++ b/codes/python/chapter_stack_and_queue/stack.py @@ -0,0 +1,10 @@ +''' +File: stack.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_tree/binary_search_tree.py b/codes/python/chapter_tree/binary_search_tree.py new file mode 100644 index 0000000000..f9dd9ec956 --- /dev/null +++ b/codes/python/chapter_tree/binary_search_tree.py @@ -0,0 +1,10 @@ +''' +File: binary_search_tree.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_tree/binary_tree.py b/codes/python/chapter_tree/binary_tree.py new file mode 100644 index 0000000000..78afa868e6 --- /dev/null +++ b/codes/python/chapter_tree/binary_tree.py @@ -0,0 +1,10 @@ +''' +File: binary_tree.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_tree/binary_tree_bfs.py b/codes/python/chapter_tree/binary_tree_bfs.py new file mode 100644 index 0000000000..43f1922060 --- /dev/null +++ b/codes/python/chapter_tree/binary_tree_bfs.py @@ -0,0 +1,10 @@ +''' +File: binary_tree_bfs.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/chapter_tree/binary_tree_dfs.py b/codes/python/chapter_tree/binary_tree_dfs.py new file mode 100644 index 0000000000..f8415ef566 --- /dev/null +++ b/codes/python/chapter_tree/binary_tree_dfs.py @@ -0,0 +1,10 @@ +''' +File: binary_tree_dfs.py +Created Time: 2022-11-25 +Author: Krahets (krahets@163.com) +''' + +import sys, os.path as osp +sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) +from include import * + diff --git a/codes/python/include/__init__.py b/codes/python/include/__init__.py new file mode 100644 index 0000000000..5939efb5a7 --- /dev/null +++ b/codes/python/include/__init__.py @@ -0,0 +1,9 @@ +import copy +import math +import random +import functools +import collections +from typing import List +from .linked_list import ListNode, list_to_linked_list, linked_list_to_list, get_list_node +from .binary_tree import TreeNode, list_to_tree, tree_to_list, get_tree_node +from .print_util import print_matrix, print_linked_list, print_tree \ No newline at end of file diff --git a/codes/python/include/__pycache__/__init__.cpython-38.pyc b/codes/python/include/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000..451b2942f4 Binary files /dev/null and b/codes/python/include/__pycache__/__init__.cpython-38.pyc differ diff --git a/codes/python/include/__pycache__/binary_tree.cpython-38.pyc b/codes/python/include/__pycache__/binary_tree.cpython-38.pyc new file mode 100644 index 0000000000..281d878c75 Binary files /dev/null and b/codes/python/include/__pycache__/binary_tree.cpython-38.pyc differ diff --git a/codes/python/include/__pycache__/linked_list.cpython-38.pyc b/codes/python/include/__pycache__/linked_list.cpython-38.pyc new file mode 100644 index 0000000000..394da81a82 Binary files /dev/null and b/codes/python/include/__pycache__/linked_list.cpython-38.pyc differ diff --git a/codes/python/include/__pycache__/print_util.cpython-38.pyc b/codes/python/include/__pycache__/print_util.cpython-38.pyc new file mode 100644 index 0000000000..7ace7e6e4a Binary files /dev/null and b/codes/python/include/__pycache__/print_util.cpython-38.pyc differ diff --git a/codes/python/include/binary_tree.py b/codes/python/include/binary_tree.py new file mode 100644 index 0000000000..d905d8270e --- /dev/null +++ b/codes/python/include/binary_tree.py @@ -0,0 +1,82 @@ +''' +File: binary_tree.py +Created Time: 2021-12-11 +Author: Krahets (krahets@163.com) +''' + +import collections + +class TreeNode: + """Definition for a binary tree node + """ + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def list_to_tree(arr): + """Generate a binary tree with a list + + Args: + arr ([type]): [description] + + Returns: + [type]: [description] + """ + if not arr: + return + i = 1 + root = TreeNode(int(arr[0])) + queue = collections.deque() + queue.append(root) + while queue: + node = queue.popleft() + if arr[i] != None: + node.left = TreeNode(int(arr[i])) + queue.append(node.left) + i += 1 + if arr[i] != None: + node.right = TreeNode(int(arr[i])) + queue.append(node.right) + i += 1 + return root + +def tree_to_list(root): + """Serialize a tree into an array + + Args: + root ([type]): [description] + + Returns: + [type]: [description] + """ + if not root: return [] + queue = collections.deque() + queue.append(root) + res = [] + while queue: + node = queue.popleft() + if node: + res.append(node.val) + queue.append(node.left) + queue.append(node.right) + else: res.append(None) + return res + +def get_tree_node(root, val): + """Get a tree node with specific value in a binary tree + + Args: + root ([type]): [description] + val ([type]): [description] + + Returns: + [type]: [description] + """ + if not root: + return + if root.val == val: + return root + left = get_tree_node(root.left, val) + right = get_tree_node(root.right, val) + return left if left else right diff --git a/codes/python/include/linked_list.py b/codes/python/include/linked_list.py new file mode 100644 index 0000000000..f6773c6f22 --- /dev/null +++ b/codes/python/include/linked_list.py @@ -0,0 +1,57 @@ +''' +File: linked_list.py +Created Time: 2021-12-11 +Author: Krahets (krahets@163.com) +''' + +class ListNode: + """Definition for a singly-linked list node + """ + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +def list_to_linked_list(arr): + """Generate a linked list with a list + + Args: + arr ([type]): [description] + + Returns: + [type]: [description] + """ + dum = head = ListNode(0) + for a in arr: + node = ListNode(a) + head.next = node + head = head.next + return dum.next + +def linked_list_to_list(head): + """Serialize a linked list into an array + + Args: + head ([type]): [description] + + Returns: + [type]: [description] + """ + arr = [] + while head: + arr.append(head.val) + head = head.next + return arr + +def get_list_node(head, val): + """Get a list node with specific value from a linked list + + Args: + head ([type]): [description] + val ([type]): [description] + + Returns: + [type]: [description] + """ + while head and head.val != val: + head = head.next + return head diff --git a/codes/python/include/print_util.py b/codes/python/include/print_util.py new file mode 100644 index 0000000000..b7c2ba2dbf --- /dev/null +++ b/codes/python/include/print_util.py @@ -0,0 +1,73 @@ +''' +File: print_util.py +Created Time: 2021-12-11 +Author: Krahets (krahets@163.com) +''' + +from .binary_tree import TreeNode, tree_to_list +from .linked_list import ListNode, linked_list_to_list + +def print_matrix(mat): + """Print a matrix + + Args: + mat ([type]): [description] + """ + pstr = [] + for arr in mat: + pstr.append(' ' + str(arr)) + + print('[\n' + ',\n'.join(pstr) + '\n]') + +def print_linked_list(head): + """Print a linked list + + Args: + head ([type]): [description] + """ + arr = linked_list_to_list(head) + print(' -> '.join([str(a) for a in arr])) + + +class Trunk: + def __init__(self, prev=None, str=None): + self.prev = prev + self.str = str + +def showTrunks(p): + if p is None: + return + showTrunks(p.prev) + print(p.str, end='') + +def print_tree(root, prev=None, isLeft=False): + """Print a binary tree + This tree printer is borrowed from TECHIE DELIGHT + https://www.techiedelight.com/c-program-print-binary-tree/ + Args: + root ([type]): [description] + prev ([type], optional): [description]. Defaults to None. + isLeft (bool, optional): [description]. Defaults to False. + """ + if root is None: + return + + prev_str = ' ' + trunk = Trunk(prev, prev_str) + print_tree(root.right, trunk, True) + + if prev is None: + trunk.str = '———' + elif isLeft: + trunk.str = '/———' + prev_str = ' |' + else: + trunk.str = '\———' + prev.str = prev_str + + showTrunks(trunk) + print(' ' + str(root.val)) + if prev: + prev.str = prev_str + trunk.str = ' |' + print_tree(root.left, trunk, False) diff --git a/docs/chapter_array_and_linkedlist/array.md b/docs/chapter_array_and_linkedlist/array.md index 12869a4a24..14a24ab0e3 100644 --- a/docs/chapter_array_and_linkedlist/array.md +++ b/docs/chapter_array_and_linkedlist/array.md @@ -33,7 +33,9 @@ comments: true === "Python" ```python title="array.py" - + """ 初始化数组 """ + arr = [0] * 5 # [ 0, 0, 0, 0, 0 ] + nums = [1, 3, 2, 5, 4] ``` ## 数组优点 @@ -74,7 +76,13 @@ elementAddr = firtstElementAddr + elementLength * elementIndex === "Python" ```python title="array.py" - + """ 随机访问元素 """ + def randomAccess(nums): + # 在区间 [0, len(nums)) 中随机抽取一个数字 + random_index = random.randint(0, len(nums)) + # 获取并返回随机元素 + random_num = nums[random_index] + return random_num ``` ## 数组缺点 @@ -106,7 +114,15 @@ elementAddr = firtstElementAddr + elementLength * elementIndex === "Python" ```python title="array.py" - + """ 扩展数组长度 """ + def extend(nums, enlarge): + # 初始化一个扩展长度后的数组 + res = [0] * (len(nums) + enlarge) + # 将原数组中的所有元素复制到新数组 + for i in range(len(nums)): + res[i] = nums[i] + # 返回扩展后的新数组 + return res ``` **数组中插入或删除元素效率低下。** 假设我们想要在数组中间某位置插入一个元素,由于数组元素在内存中是 “紧挨着的” ,它们之间没有空间再放任何数据。因此,我们不得不将此索引之后的所有元素都向后移动一位,然后再把元素赋值给该索引。删除元素也是类似,需要把此索引之后的元素都向前移动一位。总体看有以下缺点: @@ -150,7 +166,19 @@ elementAddr = firtstElementAddr + elementLength * elementIndex === "Python" ```python title="array.py" - + """ 在数组的索引 index 处插入元素 num """ + def insert(nums, num, index): + # 把索引 index 以及之后的所有元素向后移动一位 + for i in range(len(nums) - 1, index - 1, -1): + nums[i] = nums[i - 1] + # 将 num 赋给 index 处元素 + nums[index] = num + + """ 删除索引 index 处元素 """ + def remove(nums, index): + # 把索引 index 之后的所有元素向前移动一位 + for i in range(index, len(nums) - 1): + nums[i] = nums[i + 1] ``` ## 数组常用操作 @@ -183,7 +211,15 @@ elementAddr = firtstElementAddr + elementLength * elementIndex === "Python" ```python title="array.py" - + """ 遍历数组 """ + def traverse(nums): + count = 0 + # 通过索引遍历数组 + for i in range(len(nums)): + count += 1 + # 直接遍历数组 + for num in nums: + count += 1 ``` **数组查找。** 通过遍历数组,查找数组内的指定元素,并输出对应索引。 @@ -210,7 +246,12 @@ elementAddr = firtstElementAddr + elementLength * elementIndex === "Python" ```python title="array.py" - + """ 在数组中查找指定元素 """ + def find(nums, target): + for i in range(len(nums)): + if nums[i] == target: + return i + return -1 ``` ## 数组典型应用 diff --git a/docs/chapter_array_and_linkedlist/linked_list.md b/docs/chapter_array_and_linkedlist/linked_list.md index 514034e25d..51da061347 100644 --- a/docs/chapter_array_and_linkedlist/linked_list.md +++ b/docs/chapter_array_and_linkedlist/linked_list.md @@ -77,7 +77,18 @@ comments: true === "Python" ```python title="" - + """ 初始化链表 1 -> 3 -> 2 -> 5 -> 4 """ + # 初始化各个结点 + n0 = ListNode(1) + n1 = ListNode(3) + n2 = ListNode(2) + n3 = ListNode(5) + n4 = ListNode(4) + # 构建引用指向 + n0.next = n1 + n1.next = n2 + n2.next = n3 + n3.next = n4 ``` ## 链表优点 @@ -118,7 +129,20 @@ comments: true === "Python" ```python title="" - + """ 在链表的结点 n0 之后插入结点 P """ + def insert(n0, P): + n1 = n0.next + n0.next = P + P.next = n1 + + """ 删除链表的结点 n0 之后的首个结点 """ + def remove(n0): + if not n0.next: + return + # n0 -> P -> n1 + P = n0.next + n1 = P.next + n0.next = n1 ``` ## 链表缺点 @@ -148,7 +172,13 @@ comments: true === "Python" ```python title="" - + """ 访问链表中索引为 index 的结点 """ + def access(head, index): + for _ in range(index): + head = head.next + if not head: + return None + return head ``` **链表的内存占用多。** 链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。 @@ -182,7 +212,15 @@ comments: true === "Python" ```python title="" - + """ 在链表中查找值为 target 的首个结点 """ + def find(head, target): + index = 0 + while head: + if head.val == target: + return index + head = head.next + index += 1 + return -1 ``` ## 常见链表类型 @@ -214,7 +252,12 @@ comments: true === "Python" ```python title="" - + """ 双向链表结点类 """ + class ListNode: + def __init__(self, x): + self.val = x # 结点值 + self.next = None # 指向后继结点的指针(引用) + self.prev = None # 指向前驱结点的指针(引用) ``` ![linkedlist_common_types](linked_list.assets/linkedlist_common_types.png) diff --git a/docs/chapter_array_and_linkedlist/list.md b/docs/chapter_array_and_linkedlist/list.md index 4f584dba2f..e6308605dd 100644 --- a/docs/chapter_array_and_linkedlist/list.md +++ b/docs/chapter_array_and_linkedlist/list.md @@ -30,7 +30,8 @@ comments: true === "Python" ```python title="list.py" - + """ 初始化列表 """ + list = [1, 3, 2, 5, 4] ``` **访问与更新元素。** 列表的底层数据结构是数组,因此可以在 $O(1)$ 时间内访问与更新元素,效率很高。 @@ -54,7 +55,11 @@ comments: true === "Python" ```python title="list.py" - + """ 访问元素 """ + num = list[1] # 访问索引 1 处的元素 + + """ 更新元素 """ + list[1] = 0 # 将索引 1 处的元素更新为 0 ``` **在列表中添加、插入、删除元素。** 相对于数组,列表可以自由地添加与删除元素。在列表尾部添加元素的时间复杂度为 $O(1)$ ,但是插入与删除元素的效率仍与数组一样低,时间复杂度为 $O(N)$ 。 @@ -88,7 +93,21 @@ comments: true === "Python" ```python title="list.py" - + """ 清空列表 """ + list.clear() + + """ 尾部添加元素 """ + list.append(1) + list.append(3) + list.append(2) + list.append(5) + list.append(4) + + """ 中间插入元素 """ + list.insert(3, 6) # 在索引 3 处插入数字 6 + + """ 删除元素 """ + list.pop(3) # 删除索引 3 处的元素 ``` **遍历列表。** 与数组一样,列表可以使用索引遍历,也可以使用 `for-each` 直接遍历。 @@ -118,7 +137,15 @@ comments: true === "Python" ```python title="list.py" - + """ 通过索引遍历列表 """ + count = 0 + for i in range(len(list)): + count += 1 + + """ 直接遍历列表元素 """ + count = 0 + for n in list: + count += 1 ``` **拼接两个列表。** 再创建一个新列表 `list1` ,我们可以将其中一个列表拼接到另一个的尾部。 @@ -140,7 +167,9 @@ comments: true === "Python" ```python title="list.py" - + """ 拼接两个列表 """ + list1 = [6, 8, 7, 10, 9] + list += list1 # 将列表 list1 拼接到 list 之后 ``` **排序列表。** 排序也是常用的方法之一,完成列表排序后,我们就可以使用在数组类算法题中经常考察的「二分查找」和「双指针」算法了。 @@ -161,7 +190,8 @@ comments: true === "Python" ```python title="list.py" - + """ 排序列表 """ + list.sort() # 排序后,列表元素从小到大排列 ``` ## 列表简易实现 * @@ -189,12 +219,12 @@ comments: true nums = new int[initialCapacity]; } - /* 获取列表容量 */ + /* 获取列表长度(即当前元素数量)*/ public int size() { return size; } - /* 获取列表长度(即当前元素数量) */ + /* 获取列表容量 */ public int capacity() { return nums.length; } @@ -269,5 +299,60 @@ comments: true === "Python" ```python title="my_list.py" - + """ 列表类简易实现 """ + class MyList: + """ 构造函数 """ + def __init__(self): + self._initial_capacity = 10 # 列表初始容量 + self._nums = [0] * self._initial_capacity # 数组(存储列表元素) + self._size = 0 # 列表长度(即当前元素数量) + self._extend_ratio = 2 # 每次列表扩容的倍数 + + """ 获取列表长度(即当前元素数量) """ + def size(self): + return self._size + + """ 获取列表容量 """ + def capacity(self): + return len(self._nums) + + """ 访问元素 """ + def get(self, index): + # 索引如果越界则抛出异常,下同 + assert index < self._size, "索引越界" + return self._nums[index] + + """ 更新元素 """ + def set(self, num, index): + assert index < self._size, "索引越界" + self._nums[index] = num + + """ 中间插入元素 """ + def add(self, num, index=-1): + assert index < self._size, "索引越界" + if index == -1: + index = self._size + # 元素数量超出容量时,触发扩容机制 + if self._size == self.capacity(): + self.extend_capacity() + # 索引 i 以及之后的元素都向后移动一位 + for j in range(self._size - 1, index - 1, -1): + self._nums[j + 1] = self._nums[j] + self._nums[index] = num + # 更新元素数量 + self._size += 1 + + """ 删除元素 """ + def remove(self, index): + assert index < self._size, "索引越界" + # 索引 i 之后的元素都向前移动一位 + for j in range(index, self._size - 1): + self._nums[j] = self._nums[j + 1] + # 更新元素数量 + self._size -= 1 + + """ 列表扩容 """ + def extend_capacity(self): + # 新建一个长度为 self._size 的数组,并将原数组拷贝到新数组 + self._nums = self._nums + [0] * self.capacity() * (self._extend_ratio - 1) ``` diff --git a/docs/chapter_dsa_introduction/index.md b/docs/chapter_dsa_introduction/index.md deleted file mode 100644 index f998ed9ddd..0000000000 --- a/docs/chapter_dsa_introduction/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -comments: true ---- - -# 算法是什么 - -听到 “算法” 这个词,我们一般会联想到数学。但实际上,大多数算法并不包含复杂的数学,而更像是在考察基本逻辑,而这些逻辑在我们日常生活中处处可见。 - -在正式介绍算法之前,我想告诉你一件有趣的事:**其实,你在过去已经学会了很多算法,并且已经习惯将它们应用到日常生活中。** 接下来,我将介绍两个具体例子来佐证。 - -**例一:拼积木。** 一套积木,除了有许多部件之外,还会附送详细的拼装说明书。我们按照说明书上一步步操作,即可拼出复杂的积木模型。 - -如果从数据结构与算法的角度看,大大小小的「积木」就是数据结构,而「拼装说明书」上的一系列步骤就是算法。 - -**例二:查字典。** 在字典中,每个汉字都有一个对应的拼音,而字典是按照拼音的英文字母表顺序排列的。假设需要在字典中查询任意一个拼音首字母为 $r$ 的字,一般我们会这样做: - -1. 打开字典大致一半页数的位置,查看此页的首字母是什么(假设为 $m$ ); -2. 由于在英文字母表中 $r$ 在 $m$ 的后面,因此应排除字典前半部分,查找范围仅剩后半部分; -3. 循环执行步骤 1-2 ,直到找到拼音首字母为 $r$ 的页码时终止。 - -=== "Step 1" - - ![look_up_dictionary_step_1](index.assets/look_up_dictionary_step_1.png) - -=== "Step 2" - - ![look_up_dictionary_step_2](index.assets/look_up_dictionary_step_2.png) - -=== "Step 3" - - ![look_up_dictionary_step_3](index.assets/look_up_dictionary_step_3.png) - -=== "Step 4" - - ![look_up_dictionary_step_4](index.assets/look_up_dictionary_step_4.png) - -=== "Step 5" - - ![look_up_dictionary_step_5](index.assets/look_up_dictionary_step_5.png) - -查字典这个小学生的标配技能,实际上就是大名鼎鼎的「二分查找」。从数据结构角度,我们可以将字典看作是一个已排序的「数组」;而从算法角度,我们可将上述查字典的一系列指令看作是「二分查找」算法。 - -小到烹饪一道菜、大到星际航行,几乎所有问题的解决都离不开算法。计算机的出现,使我们可以通过编程将数据结构存储在内存中,也可以编写代码来调用 CPU, GPU 执行算法,从而将生活中的问题搬运到计算机中,更加高效地解决各式各样的复杂问题。 - -!!! tip - - 读到这里,如果你感到对数据结构、算法、数组、二分查找等此类概念一知半解,那么就太好了!因为这正是本书存在的价值,接下来,本书将会一步步地引导你进入数据结构与算法的知识殿堂。 - -## 算法是什么? - -「算法 Algorithm」是在有限时间内解决问题的一组指令或操作步骤。算法具有以下特性: - -- 问题是明确的,需要拥有明确的输入和输出定义。 -- 解具有确定性,即给定相同输入时,输出一定相同。 -- 具有可行性,可在有限步骤、有限时间、有限内存空间下完成。 -- 独立于编程语言,即可用多种语言实现。 - -## 数据结构是什么? - -「数据结构 Data Structure」是在计算机中组织与存储数据的方式。为了提高数据存储和操作性能,数据结构的设计原则有: - -- 空间占用尽可能小,节省计算机内存。 -- 数据操作尽量快,包括数据访问、添加、删除、更新等。 -- 提供简洁的数据表示和逻辑信息,以便算法高效运行。 - -数据结构的设计是一个充满权衡的过程,这意味着如果获得某方面的优势,则往往需要在另一方面做出妥协。例如,链表相对于数组,数据添加删除操作更加方便,但牺牲了数据的访问速度;图相对于链表,提供了更多的逻辑信息,但需要占用更多的内存空间。 - -## 数据结构与算法的关系 - -「数据结构」与「算法」是高度相关、紧密嵌合的,体现在: - -- 数据结构是算法的底座。数据结构为算法提供结构化存储的数据,以及操作数据的对应方法。 -- 算法是发挥数据结构优势的舞台。数据结构仅存储数据信息,结合算法才可解决特定问题。 -- 算法有对应最优的数据结构。给定算法,一般可基于不同的数据结构实现,而最终执行效率往往相差很大。 - -如果将数据结构与算法比作「LEGO 乐高」,数据结构就是乐高「积木」,而算法就是把积木拼成目标形态的一系列「操作步骤」。 - -![relationship_between_data_structure_and_algorithm](index.assets/relationship_between_data_structure_and_algorithm.png) - -

Fig. 数据结构与算法的关系

- -!!! tip "约定俗成的习惯" - - 在实际讨论中,我们通常会将「数据结构与算法」简称为「算法」。例如,我们熟称的 LeetCode 算法题目,实际上同时考察了数据结构和算法两部分知识。 diff --git a/docs/chapter_dsa_introduction/index.assets/look_up_dictionary.png b/docs/chapter_introduction/index.assets/look_up_dictionary.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/look_up_dictionary.png rename to docs/chapter_introduction/index.assets/look_up_dictionary.png diff --git a/docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_1.png b/docs/chapter_introduction/index.assets/look_up_dictionary_step_1.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_1.png rename to docs/chapter_introduction/index.assets/look_up_dictionary_step_1.png diff --git a/docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_2.png b/docs/chapter_introduction/index.assets/look_up_dictionary_step_2.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_2.png rename to docs/chapter_introduction/index.assets/look_up_dictionary_step_2.png diff --git a/docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_3.png b/docs/chapter_introduction/index.assets/look_up_dictionary_step_3.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_3.png rename to docs/chapter_introduction/index.assets/look_up_dictionary_step_3.png diff --git a/docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_4.png b/docs/chapter_introduction/index.assets/look_up_dictionary_step_4.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_4.png rename to docs/chapter_introduction/index.assets/look_up_dictionary_step_4.png diff --git a/docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_5.png b/docs/chapter_introduction/index.assets/look_up_dictionary_step_5.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/look_up_dictionary_step_5.png rename to docs/chapter_introduction/index.assets/look_up_dictionary_step_5.png diff --git a/docs/chapter_dsa_introduction/index.assets/relationship_between_data_structure_and_algorithm.png b/docs/chapter_introduction/index.assets/relationship_between_data_structure_and_algorithm.png similarity index 100% rename from docs/chapter_dsa_introduction/index.assets/relationship_between_data_structure_and_algorithm.png rename to docs/chapter_introduction/index.assets/relationship_between_data_structure_and_algorithm.png diff --git a/docs/chapter_introduction/index.md b/docs/chapter_introduction/index.md index 0d7dfdfc14..f998ed9ddd 100644 --- a/docs/chapter_introduction/index.md +++ b/docs/chapter_introduction/index.md @@ -2,127 +2,83 @@ comments: true --- -# 关于本书 +# 算法是什么 -五年前发生的一件事,成为了我职业生涯的重要转折点。当时的我在交大读研,对互联网求职一无所知,但仍然硬着头皮申请了 Microsoft 软件工程师实习。面试官让我在白板上写出 “快速排序” 代码,我畏畏缩缩地写了一个 “冒泡排序” ,并且还写错了` (ToT) ` 。从面试官的表情上,我看到了一个大大的 "GG" 。 +听到 “算法” 这个词,我们一般会联想到数学。但实际上,大多数算法并不包含复杂的数学,而更像是在考察基本逻辑,而这些逻辑在我们日常生活中处处可见。 -此次失利倒逼我开始刷算法题。我采用 “扫雷游戏” 式的学习方法,两眼一抹黑刷题,扫到不会的 “雷” 就通过查资料把它 “排掉” ,配合周期性总结,逐渐形成了数据结构与算法的知识图景。幸运地,我在秋招斩获了多家大厂的 Offer 。 +在正式介绍算法之前,我想告诉你一件有趣的事:**其实,你在过去已经学会了很多算法,并且已经习惯将它们应用到日常生活中。** 接下来,我将介绍两个具体例子来佐证。 -回想自己当初在 “扫雷式” 刷题中被炸的满头包的痛苦,思考良久,我意识到一本 “前期刷题必看” 的读物可以使算法小白少走许多弯路。写作意愿滚滚袭来,那就动笔吧: +**例一:拼积木。** 一套积木,除了有许多部件之外,还会附送详细的拼装说明书。我们按照说明书上一步步操作,即可拼出复杂的积木模型。 -

Hello,算法!

+如果从数据结构与算法的角度看,大大小小的「积木」就是数据结构,而「拼装说明书」上的一系列步骤就是算法。 -## 读者对象 +**例二:查字典。** 在字典中,每个汉字都有一个对应的拼音,而字典是按照拼音的英文字母表顺序排列的。假设需要在字典中查询任意一个拼音首字母为 $r$ 的字,一般我们会这样做: -!!! success "前置条件" +1. 打开字典大致一半页数的位置,查看此页的首字母是什么(假设为 $m$ ); +2. 由于在英文字母表中 $r$ 在 $m$ 的后面,因此应排除字典前半部分,查找范围仅剩后半部分; +3. 循环执行步骤 1-2 ,直到找到拼音首字母为 $r$ 的页码时终止。 - 您需要至少具备任一语言的编程基础,能够阅读和编写简单代码。 +=== "Step 1" -如果您是 **算法初学者**,完全没有接触过算法,或者已经有少量刷题,对数据结构与算法有朦胧的理解,在会与不会之间反复横跳,那么这本书就是为您而写!本书能够带来: + ![look_up_dictionary_step_1](index.assets/look_up_dictionary_step_1.png) -- 了解刷题所需的 **数据结构**,包括常用操作、优势和劣势、典型应用、实现方法等。 -- 学习各类 **算法**,介绍算法的设计思想、运行效率、优势劣势、实现方法等。 -- 可一键运行的 **配套代码**,包含详细注释,帮助你通过实践加深理解。 +=== "Step 2" -如果您是 **算法熟练工**,已经积累一定刷题量,接触过大多数题型,那么本书内容对你来说可能稍显基础,但仍能够带来以下价值: + ![look_up_dictionary_step_2](index.assets/look_up_dictionary_step_2.png) -- 本书篇幅不长,可以帮助你提纲挈领地回顾算法知识。 -- 书中包含许多对比性、总结性的算法内容,可以帮助你梳理算法知识体系。 -- 源代码实现了各种经典数据结构和算法,可以作为 “刷题工具库” 来使用。 +=== "Step 3" -如果您是 **算法大佬**,请受我膜拜!希望您可以抽时间提出意见建议,或者[一起参与创作](https://www.hello-algo.com/chapter_introduction/contribution/),帮助各位同学获取更好的学习内容,感谢! + ![look_up_dictionary_step_3](index.assets/look_up_dictionary_step_3.png) -## 内容结构 +=== "Step 4" -本书主要内容分为复杂度分析、数据结构、算法三个部分。 + ![look_up_dictionary_step_4](index.assets/look_up_dictionary_step_4.png) -![mindmap](index.assets/mindmap.png) +=== "Step 5" -

Fig. 知识点思维导图

+ ![look_up_dictionary_step_5](index.assets/look_up_dictionary_step_5.png) -### 复杂度分析 +查字典这个小学生的标配技能,实际上就是大名鼎鼎的「二分查找」。从数据结构角度,我们可以将字典看作是一个已排序的「数组」;而从算法角度,我们可将上述查字典的一系列指令看作是「二分查找」算法。 -首先介绍数据结构与算法的评价维度、算法效率的评估方法,引出了计算复杂度概念。 +小到烹饪一道菜、大到星际航行,几乎所有问题的解决都离不开算法。计算机的出现,使我们可以通过编程将数据结构存储在内存中,也可以编写代码来调用 CPU, GPU 执行算法,从而将生活中的问题搬运到计算机中,更加高效地解决各式各样的复杂问题。 -接下来,从 **函数渐进上界** 入手,分别介绍了 **时间复杂度** 和 **空间复杂度** ,包括推算方法、常见类型、示例等。同时,剖析了 **最差、最佳、平均** 时间复杂度的联系与区别。 +!!! tip -### 数据结构 + 读到这里,如果你感到对数据结构、算法、数组、二分查找等此类概念一知半解,那么就太好了!因为这正是本书存在的价值,接下来,本书将会一步步地引导你进入数据结构与算法的知识殿堂。 -首先介绍了常用的 **基本数据类型** 、以及它们是如何在内存中存储的。 +## 算法是什么? -接下来,介绍了两种 **数据结构分类方法** ,包括逻辑结构与物理结构。 +「算法 Algorithm」是在有限时间内解决问题的一组指令或操作步骤。算法具有以下特性: -后续展开介绍了 **数组、链表、栈、队列、散列表、树、堆、图** 等数据结构,关心以下内容: +- 问题是明确的,需要拥有明确的输入和输出定义。 +- 解具有确定性,即给定相同输入时,输出一定相同。 +- 具有可行性,可在有限步骤、有限时间、有限内存空间下完成。 +- 独立于编程语言,即可用多种语言实现。 -- 基本定义:数据结构的设计来源、存在意义; -- 主要特点:在各项数据操作中的优势、劣势; -- 常用操作:例如访问、更新、插入、删除、遍历、搜索等; -- 常见类型:在算法题或工程实际中,经常碰到的数据结构类型; -- 典型应用:此数据结构经常搭配哪些算法使用; -- 实现方法:对于重要的数据结构,将给出完整的实现示例; +## 数据结构是什么? -### 算法 +「数据结构 Data Structure」是在计算机中组织与存储数据的方式。为了提高数据存储和操作性能,数据结构的设计原则有: -包括 **查找算法、排序算法、搜索与回溯、动态规划、分治算法**,内容包括: +- 空间占用尽可能小,节省计算机内存。 +- 数据操作尽量快,包括数据访问、添加、删除、更新等。 +- 提供简洁的数据表示和逻辑信息,以便算法高效运行。 -- 基本定义:算法的设计思想; -- 主要特点:使用前置条件、优势和劣势; -- 算法效率:最差和平均时间复杂度、空间复杂度; -- 实现方法:完整的算法实现,以及优化措施; -- 示例题目:结合例题加深理解; +数据结构的设计是一个充满权衡的过程,这意味着如果获得某方面的优势,则往往需要在另一方面做出妥协。例如,链表相对于数组,数据添加删除操作更加方便,但牺牲了数据的访问速度;图相对于链表,提供了更多的逻辑信息,但需要占用更多的内存空间。 -## 配套代码 +## 数据结构与算法的关系 -完整代码托管在 [GitHub 仓库](https://github.com/krahets/hello-algo) ,皆可一键运行。 +「数据结构」与「算法」是高度相关、紧密嵌合的,体现在: -!!! tip "前置工作" +- 数据结构是算法的底座。数据结构为算法提供结构化存储的数据,以及操作数据的对应方法。 +- 算法是发挥数据结构优势的舞台。数据结构仅存储数据信息,结合算法才可解决特定问题。 +- 算法有对应最优的数据结构。给定算法,一般可基于不同的数据结构实现,而最终执行效率往往相差很大。 - 1. [编程环境安装](https://www.hello-algo.com/chapter_introduction/installation/) ,若有请跳过 - 2. 代码下载与使用方法请见 [如何使用本书](https://www.hello-algo.com/chapter_introduction/suggestions/#_4) +如果将数据结构与算法比作「LEGO 乐高」,数据结构就是乐高「积木」,而算法就是把积木拼成目标形态的一系列「操作步骤」。 -## 风格约定 +![relationship_between_data_structure_and_algorithm](index.assets/relationship_between_data_structure_and_algorithm.png) -- 文章中的重要名词会用「」符号标注,例如「数组 Array」。名词混淆会导致不必要的歧义,因此最好可以记住这类名词(包括中文和英文),以便后续阅读文献时使用。 -- 重点内容、总起句、总结句会被 **加粗** ,此类文字值得更多关注。 -- 专有名词和有特指含义的词句会使用 “ ” 标注,以避免歧义。 -- 标题后标注 * 符号的是选读章节,如果你的时间有限,可以先跳过这些章节。 +

Fig. 数据结构与算法的关系

-## 本书特点 * +!!! tip "约定俗成的习惯" -??? abstract "默认折叠,可以跳过" - - **以实践为主。** 我们知道,学习英语期间光啃书本是远远不够的,需要多听、多说、多写,在实践中培养语感、积累经验。编程语言也是一门语言,因此学习方法也应是类似的,需要多看优秀代码、多敲键盘、多思考代码逻辑。 - - 本书的理论部分占少量篇幅,主要分为两类:一是基础且必要的概念知识,以培养读者对于算法的感性认识;二是重要的分类、对比或总结,这是为了帮助你站在更高视角俯瞰各个知识点,形成连点成面的效果。 - - 实践部分主要由示例和代码组成。代码配有简要注释,复杂示例会尽可能地使用视觉化的形式呈现。我强烈建议读者对照着代码自己敲一遍,如果时间有限,也至少逐行读、复制并运行一遍,配合着讲解将代码吃透。 - - **视觉化学习。** 信息时代以来,视觉化的脚步从未停止。媒体形式经历了文字短信、图文 Email 、动图、短(长)视频、交互式 Web 、3D 游戏等演变过程,信息的视觉化程度越来越高、愈加符合人类感官、信息传播效率大大提升。科技界也在向视觉化迈进,iPhone 就是一个典型例子,其相对于传统手机是高度视觉化的,包含精心设计的字体、主题配色、交互动画等。 - - 近两年,短视频成为最受欢迎的信息媒介,可以在短时间内将高密度的信息 “灌” 给我们,有着极其舒适的观看体验。阅读则不然,读者与书本之间天然存在一种 “疏离感”,我们看书会累、会走神、会停下来想其他事、会划下喜欢的句子、会思考某一片段的含义,这种疏离感给了读者与书本之间对话的可能,拓宽了想象空间。 - - 本书作为一本入门教材,希望可以保有书本的 “慢节奏” ,但也会避免与读者产生过多 “疏离感” ,而是努力将知识完整清晰地推送到你聪明的小脑袋瓜中。我将采用视觉化的方式(例如配图、动画),尽我可能清晰易懂地讲解复杂概念和抽象示例。 - - **内容精简化。** 大多数的经典教科书,会把每个主题都讲的很透彻。虽然透彻性正是其获得读者青睐的原因,但对于想要快速入门的初学者来说,这些教材的实用性不足。本书会避免引入非必要的概念、名词、定义等,也避免展开不必要的理论分析,毕竟这不是一本真正意义上的教材,主要任务是尽快地带领读者入门。 - - 引入一些生活案例或趣味内容,非常适合作为知识点的引子或者解释的补充,但当融入过多额外元素时,内容会稍显冗长,也许反而使读者容易迷失、抓不住重点,这也是本书需要避免的。 - - 敲代码如同写字,“美” 是统一的追求。本书力求美观的代码,保证规范的变量命名、统一的空格与换行、对齐的缩进、整齐的注释等。 - -## 致谢 - -感谢本开源书的每一位撰稿人,是他们的无私奉献让这本书变得更好,他们的 GitHub ID(首次提交时间排序)为:Krahets, *(等待下一位创作者)* - -本书的成书过程中,我获得了许多人的帮助,包括但不限于: - -- 感谢我的女朋友泡泡担任本书的首位读者,从算法小白的视角为本书的写作提出了许多建议,使这本书更加适合算法初学者来阅读。 - -- 感谢腾宝、琦宝、飞宝为本书起了个响当当的名字,好听又有梗,直接唤起我最初敲下第一行代码 "Hello, World!" 的回忆。 - -- 感谢苏潼为本书设计了封面和 LOGO ,我有些强迫症,前后多次修改,谢谢你的耐心。 - -- 感谢我的导师李博,在小酌畅谈时你告诉我 “想做就去做” ,坚定了我写这本书的决心。 - -在写作过程中,我阅读了许多与数据结构与算法的书籍材料,学习到了许多知识,感谢前辈们的精彩创作。 - -感谢父母,你们一贯的支持与鼓励给了我自由度来做这些有趣的事。 + 在实际讨论中,我们通常会将「数据结构与算法」简称为「算法」。例如,我们熟称的 LeetCode 算法题目,实际上同时考察了数据结构和算法两部分知识。 diff --git a/docs/chapter_introduction/about_me.assets/profile.png b/docs/chapter_preface/about_me.assets/profile.png similarity index 100% rename from docs/chapter_introduction/about_me.assets/profile.png rename to docs/chapter_preface/about_me.assets/profile.png diff --git a/docs/chapter_introduction/about_me.md b/docs/chapter_preface/about_me.md similarity index 99% rename from docs/chapter_introduction/about_me.md rename to docs/chapter_preface/about_me.md index 01bdca309d..632d51a991 100644 --- a/docs/chapter_introduction/about_me.md +++ b/docs/chapter_preface/about_me.md @@ -5,4 +5,3 @@

力扣(LeetCode)全网阅读量最高博主

分享近百道算法题解,累积回复数千读者的评论问题

创作 LeetBook《图解算法数据结构》,已免费售出 21 万本

- diff --git a/docs/chapter_introduction/contribution.assets/edit_markdown.png b/docs/chapter_preface/contribution.assets/edit_markdown.png similarity index 100% rename from docs/chapter_introduction/contribution.assets/edit_markdown.png rename to docs/chapter_preface/contribution.assets/edit_markdown.png diff --git a/docs/chapter_introduction/contribution.md b/docs/chapter_preface/contribution.md similarity index 100% rename from docs/chapter_introduction/contribution.md rename to docs/chapter_preface/contribution.md diff --git a/docs/chapter_introduction/index.assets/learning_route.png b/docs/chapter_preface/index.assets/learning_route.png similarity index 100% rename from docs/chapter_introduction/index.assets/learning_route.png rename to docs/chapter_preface/index.assets/learning_route.png diff --git a/docs/chapter_introduction/index.assets/mindmap.png b/docs/chapter_preface/index.assets/mindmap.png similarity index 100% rename from docs/chapter_introduction/index.assets/mindmap.png rename to docs/chapter_preface/index.assets/mindmap.png diff --git a/docs/chapter_preface/index.md b/docs/chapter_preface/index.md new file mode 100644 index 0000000000..039b99a18f --- /dev/null +++ b/docs/chapter_preface/index.md @@ -0,0 +1,128 @@ +--- +comments: true +--- + +# 关于本书 + +五年前发生的一件事,成为了我职业生涯的重要转折点。当时的我在交大读研,对互联网求职一无所知,但仍然硬着头皮申请了 Microsoft 软件工程师实习。面试官让我在白板上写出 “快速排序” 代码,我畏畏缩缩地写了一个 “冒泡排序” ,并且还写错了` (ToT) ` 。从面试官的表情上,我看到了一个大大的 "GG" 。 + +此次失利倒逼我开始刷算法题。我采用 “扫雷游戏” 式的学习方法,两眼一抹黑刷题,扫到不会的 “雷” 就通过查资料把它 “排掉” ,配合周期性总结,逐渐形成了数据结构与算法的知识图景。幸运地,我在秋招斩获了多家大厂的 Offer 。 + +回想自己当初在 “扫雷式” 刷题中被炸的满头包的痛苦,思考良久,我意识到一本 “前期刷题必看” 的读物可以使算法小白少走许多弯路。写作意愿滚滚袭来,那就动笔吧: + +

Hello,算法!

+ +## 读者对象 + +!!! success "前置条件" + + 您需要至少具备任一语言的编程基础,能够阅读和编写简单代码。 + +如果您是 **算法初学者**,完全没有接触过算法,或者已经有少量刷题,对数据结构与算法有朦胧的理解,在会与不会之间反复横跳,那么这本书就是为您而写!本书能够带来: + +- 了解刷题所需的 **数据结构**,包括常用操作、优势和劣势、典型应用、实现方法等。 +- 学习各类 **算法**,介绍算法的设计思想、运行效率、优势劣势、实现方法等。 +- 可一键运行的 **配套代码**,包含详细注释,帮助你通过实践加深理解。 + +如果您是 **算法熟练工**,已经积累一定刷题量,接触过大多数题型,那么本书内容对你来说可能稍显基础,但仍能够带来以下价值: + +- 本书篇幅不长,可以帮助你提纲挈领地回顾算法知识。 +- 书中包含许多对比性、总结性的算法内容,可以帮助你梳理算法知识体系。 +- 源代码实现了各种经典数据结构和算法,可以作为 “刷题工具库” 来使用。 + +如果您是 **算法大佬**,请受我膜拜!希望您可以抽时间提出意见建议,或者[一起参与创作](https://www.hello-algo.com/chapter_preface/contribution/),帮助各位同学获取更好的学习内容,感谢! + +## 内容结构 + +本书主要内容分为复杂度分析、数据结构、算法三个部分。 + +![mindmap](index.assets/mindmap.png) + +

Fig. 知识点思维导图

+ +### 复杂度分析 + +首先介绍数据结构与算法的评价维度、算法效率的评估方法,引出了计算复杂度概念。 + +接下来,从 **函数渐进上界** 入手,分别介绍了 **时间复杂度** 和 **空间复杂度** ,包括推算方法、常见类型、示例等。同时,剖析了 **最差、最佳、平均** 时间复杂度的联系与区别。 + +### 数据结构 + +首先介绍了常用的 **基本数据类型** 、以及它们是如何在内存中存储的。 + +接下来,介绍了两种 **数据结构分类方法** ,包括逻辑结构与物理结构。 + +后续展开介绍了 **数组、链表、栈、队列、散列表、树、堆、图** 等数据结构,关心以下内容: + +- 基本定义:数据结构的设计来源、存在意义; +- 主要特点:在各项数据操作中的优势、劣势; +- 常用操作:例如访问、更新、插入、删除、遍历、搜索等; +- 常见类型:在算法题或工程实际中,经常碰到的数据结构类型; +- 典型应用:此数据结构经常搭配哪些算法使用; +- 实现方法:对于重要的数据结构,将给出完整的实现示例; + +### 算法 + +包括 **查找算法、排序算法、搜索与回溯、动态规划、分治算法**,内容包括: + +- 基本定义:算法的设计思想; +- 主要特点:使用前置条件、优势和劣势; +- 算法效率:最差和平均时间复杂度、空间复杂度; +- 实现方法:完整的算法实现,以及优化措施; +- 示例题目:结合例题加深理解; + +## 配套代码 + +完整代码托管在 [GitHub 仓库](https://github.com/krahets/hello-algo) ,皆可一键运行。 + +!!! tip "前置工作" + + 1. [编程环境安装](https://www.hello-algo.com/chapter_preface/installation/) ,若有请跳过 + 2. 代码下载与使用方法请见 [如何使用本书](https://www.hello-algo.com/chapter_preface/suggestions/#_4) + +## 风格约定 + +- 文章中的重要名词会用「」符号标注,例如「数组 Array」。名词混淆会导致不必要的歧义,因此最好可以记住这类名词(包括中文和英文),以便后续阅读文献时使用。 +- 重点内容、总起句、总结句会被 **加粗** ,此类文字值得更多关注。 +- 专有名词和有特指含义的词句会使用 “ ” 标注,以避免歧义。 +- 标题后标注 * 符号的是选读章节,如果你的时间有限,可以先跳过这些章节。 + +## 本书特点 * + +??? abstract "默认折叠,可以跳过" + + **以实践为主。** 我们知道,学习英语期间光啃书本是远远不够的,需要多听、多说、多写,在实践中培养语感、积累经验。编程语言也是一门语言,因此学习方法也应是类似的,需要多看优秀代码、多敲键盘、多思考代码逻辑。 + + 本书的理论部分占少量篇幅,主要分为两类:一是基础且必要的概念知识,以培养读者对于算法的感性认识;二是重要的分类、对比或总结,这是为了帮助你站在更高视角俯瞰各个知识点,形成连点成面的效果。 + + 实践部分主要由示例和代码组成。代码配有简要注释,复杂示例会尽可能地使用视觉化的形式呈现。我强烈建议读者对照着代码自己敲一遍,如果时间有限,也至少逐行读、复制并运行一遍,配合着讲解将代码吃透。 + + **视觉化学习。** 信息时代以来,视觉化的脚步从未停止。媒体形式经历了文字短信、图文 Email 、动图、短(长)视频、交互式 Web 、3D 游戏等演变过程,信息的视觉化程度越来越高、愈加符合人类感官、信息传播效率大大提升。科技界也在向视觉化迈进,iPhone 就是一个典型例子,其相对于传统手机是高度视觉化的,包含精心设计的字体、主题配色、交互动画等。 + + 近两年,短视频成为最受欢迎的信息媒介,可以在短时间内将高密度的信息 “灌” 给我们,有着极其舒适的观看体验。阅读则不然,读者与书本之间天然存在一种 “疏离感”,我们看书会累、会走神、会停下来想其他事、会划下喜欢的句子、会思考某一片段的含义,这种疏离感给了读者与书本之间对话的可能,拓宽了想象空间。 + + 本书作为一本入门教材,希望可以保有书本的 “慢节奏” ,但也会避免与读者产生过多 “疏离感” ,而是努力将知识完整清晰地推送到你聪明的小脑袋瓜中。我将采用视觉化的方式(例如配图、动画),尽我可能清晰易懂地讲解复杂概念和抽象示例。 + + **内容精简化。** 大多数的经典教科书,会把每个主题都讲的很透彻。虽然透彻性正是其获得读者青睐的原因,但对于想要快速入门的初学者来说,这些教材的实用性不足。本书会避免引入非必要的概念、名词、定义等,也避免展开不必要的理论分析,毕竟这不是一本真正意义上的教材,主要任务是尽快地带领读者入门。 + + 引入一些生活案例或趣味内容,非常适合作为知识点的引子或者解释的补充,但当融入过多额外元素时,内容会稍显冗长,也许反而使读者容易迷失、抓不住重点,这也是本书需要避免的。 + + 敲代码如同写字,“美” 是统一的追求。本书力求美观的代码,保证规范的变量命名、统一的空格与换行、对齐的缩进、整齐的注释等。 + +## 致谢 + +感谢本开源书的每一位撰稿人,是他们的无私奉献让这本书变得更好,他们的 GitHub ID(按首次提交时间排序)为:krahets, *(等待下一位创作者)* + +本书的成书过程中,我获得了许多人的帮助,包括但不限于: + +- 感谢我的女朋友泡泡担任本书的首位读者,从算法小白的视角为本书的写作提出了许多建议,使这本书更加适合算法初学者来阅读。 + +- 感谢腾宝、琦宝、飞宝为本书起了个响当当的名字,好听又有梗,直接唤起我最初敲下第一行代码 "Hello, World!" 的回忆。 + +- 感谢苏潼为本书设计了封面和 LOGO ,我有些强迫症,前后多次修改,谢谢你的耐心。 + +- 感谢我的导师李博,在小酌畅谈时你告诉我 “想做就去做” ,坚定了我写这本书的决心。 + +在写作过程中,我阅读了许多与数据结构与算法的书籍材料,学习到了许多知识,感谢前辈们的精彩创作。 + +感谢父母,你们一贯的支持与鼓励给了我自由度来做这些有趣的事。 diff --git a/docs/chapter_introduction/installation.assets/image-20221117201957848.png b/docs/chapter_preface/installation.assets/image-20221117201957848.png similarity index 100% rename from docs/chapter_introduction/installation.assets/image-20221117201957848.png rename to docs/chapter_preface/installation.assets/image-20221117201957848.png diff --git a/docs/chapter_introduction/installation.assets/image-20221118013006841.png b/docs/chapter_preface/installation.assets/image-20221118013006841.png similarity index 100% rename from docs/chapter_introduction/installation.assets/image-20221118013006841.png rename to docs/chapter_preface/installation.assets/image-20221118013006841.png diff --git a/docs/chapter_introduction/installation.assets/image-20221118013751773.png b/docs/chapter_preface/installation.assets/image-20221118013751773.png similarity index 100% rename from docs/chapter_introduction/installation.assets/image-20221118013751773.png rename to docs/chapter_preface/installation.assets/image-20221118013751773.png diff --git a/docs/chapter_introduction/installation.assets/vscode_installation.png b/docs/chapter_preface/installation.assets/vscode_installation.png similarity index 100% rename from docs/chapter_introduction/installation.assets/vscode_installation.png rename to docs/chapter_preface/installation.assets/vscode_installation.png diff --git a/docs/chapter_introduction/installation.md b/docs/chapter_preface/installation.md similarity index 100% rename from docs/chapter_introduction/installation.md rename to docs/chapter_preface/installation.md diff --git a/docs/chapter_introduction/suggestions.assets/algorithm_animation.gif b/docs/chapter_preface/suggestions.assets/algorithm_animation.gif similarity index 100% rename from docs/chapter_introduction/suggestions.assets/algorithm_animation.gif rename to docs/chapter_preface/suggestions.assets/algorithm_animation.gif diff --git a/docs/chapter_introduction/suggestions.assets/code_md_to_repo.png b/docs/chapter_preface/suggestions.assets/code_md_to_repo.png similarity index 100% rename from docs/chapter_introduction/suggestions.assets/code_md_to_repo.png rename to docs/chapter_preface/suggestions.assets/code_md_to_repo.png diff --git a/docs/chapter_introduction/suggestions.assets/comment.gif b/docs/chapter_preface/suggestions.assets/comment.gif similarity index 100% rename from docs/chapter_introduction/suggestions.assets/comment.gif rename to docs/chapter_preface/suggestions.assets/comment.gif diff --git a/docs/chapter_introduction/suggestions.assets/download_code.png b/docs/chapter_preface/suggestions.assets/download_code.png similarity index 100% rename from docs/chapter_introduction/suggestions.assets/download_code.png rename to docs/chapter_preface/suggestions.assets/download_code.png diff --git a/docs/chapter_introduction/suggestions.assets/learning_route.png b/docs/chapter_preface/suggestions.assets/learning_route.png similarity index 100% rename from docs/chapter_introduction/suggestions.assets/learning_route.png rename to docs/chapter_preface/suggestions.assets/learning_route.png diff --git a/docs/chapter_introduction/suggestions.assets/running_code.gif b/docs/chapter_preface/suggestions.assets/running_code.gif similarity index 100% rename from docs/chapter_introduction/suggestions.assets/running_code.gif rename to docs/chapter_preface/suggestions.assets/running_code.gif diff --git a/docs/chapter_introduction/suggestions.md b/docs/chapter_preface/suggestions.md similarity index 97% rename from docs/chapter_introduction/suggestions.md rename to docs/chapter_preface/suggestions.md index 57a1a5e63d..31f85ffdad 100644 --- a/docs/chapter_introduction/suggestions.md +++ b/docs/chapter_preface/suggestions.md @@ -16,7 +16,7 @@ comments: true !!! tip "前置工作" - 安装本地编程环境。若无,可以参照下节 [编程环境安装](https://www.hello-algo.com/chapter_introduction/installation/) 。 + 安装本地编程环境。若无,可以参照下节 [编程环境安装](https://www.hello-algo.com/chapter_preface/installation/) 。 ### 下载代码仓 diff --git a/docs/index.md b/docs/index.md index d10bb760bf..8a36a6c3d7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -53,6 +53,3 @@ hide:

“追风赶月莫停留,平芜尽处是春山“

一起加油!

- ---- - diff --git a/docs/leetcode.md b/docs/leetcode.md index 06d79c9d46..2124492008 100644 --- a/docs/leetcode.md +++ b/docs/leetcode.md @@ -44,7 +44,7 @@ Hello!我是「Krahets」,是一个分享了许多题解、编写了 LeetBoo 本书是我利用业余时间创作,完全开源免费,不会收取任何费用。 -本书定期更新中,希望您可以一同参与到本书的创作中来,详情见 [一起参与创作](https://www.hello-algo.com/chapter_introduction/contribution/) 。 +本书定期更新中,希望您可以一同参与到本书的创作中来,详情见 [一起参与创作](https://www.hello-algo.com/chapter_preface/contribution/) 。 - 如果发现笔误、无效链接、内容缺失、文字歧义、解释不清晰、行文结构不合理等问题,烦请您帮忙修正内容,以帮助其他读者获取更优质的学习内容。 - 非常欢迎您和我一同来创作本书,包括重写某章节、新增章节、翻译代码至其他编程语言等,如果有意请与我联系或在楼下评论。 diff --git a/mkdocs.yml b/mkdocs.yml index 80dd41044c..3957218bea 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,6 +1,6 @@ # Project information site_name: Hello 算法 -site_url: https://krahets.github.io/hello-algo/ +site_url: https://www.hello-algo.com/ site_author: Krahets site_description: Your first book to learn Data Structure And Algorithm. # Repository @@ -119,13 +119,13 @@ extra_css: # Page tree nav: - 关于本书: - - chapter_introduction/index.md - - 如何使用本书: chapter_introduction/suggestions.md - - 编程环境安装: chapter_introduction/installation.md - - 一起参与创作: chapter_introduction/contribution.md - - 关于作者: chapter_introduction/about_me.md + - chapter_preface/index.md + - 如何使用本书: chapter_preface/suggestions.md + - 编程环境安装: chapter_preface/installation.md + - 一起参与创作: chapter_preface/contribution.md + - 关于作者: chapter_preface/about_me.md - 算法是什么: - - chapter_dsa_introduction/index.md + - chapter_introduction/index.md - 计算复杂度: - 算法效率评估: chapter_computational_complexity/performance_evaluation.md - 时间复杂度: chapter_computational_complexity/time_complexity.md