Rearrange the chapters.

Start to translate codes from Java to Python.
This commit is contained in:
krahets 2022-11-25 02:04:38 +08:00
parent e784cd1e52
commit 9a861140d8
124 changed files with 1318 additions and 188 deletions

View File

@ -27,10 +27,10 @@
本书是我利用业余时间创作,完全开源免费,不会收取任何费用。
本书定期更新中,希望您可以一同参与到本书的创作中来,详情见 [一起参与创作](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 支持一下,谢谢!

View File

@ -0,0 +1,6 @@
/*
* File: array.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: linked_list.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: list.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: my_list.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: leetcode_two_sum.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: space_complexity_types.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: time_complexity_types.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: worst_best_time_complexity.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: binary_search.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: hashing_search.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: linear_search.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: bubble_sort.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: insertion_sort.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: merge_sort.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: quick_sort.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: array_queue.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: array_stack.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: deque.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: linkedlist_queue.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: linkedlist_stack.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: queue.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: stack.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: binary_search_tree.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: binary_tree.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: binary_tree_bfs.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,6 @@
/*
* File: binary_tree_dfs.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/

View File

@ -0,0 +1,50 @@
/*
* File: PrintUtil.hpp
* Created Time: 2021-12-19
* Author: Krahets (krahets@163.com)
*/
#pragma once
#include <iostream>
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<int> 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;
}

View File

@ -0,0 +1,197 @@
/*
* File: PrintUtil.hpp
* Created Time: 2021-12-19
* Author: Krahets (krahets@163.com)
*/
#pragma once
#include <iostream>
#include <string>
#include <sstream>
#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 <typename T>
static int vecFind(const vector<T>& 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 <typename T>
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 <typename T>
static string getVectorString(vector<T> &list) {
return "[" + strJoin(", ", list) + "]";
}
/**
* @brief Print a vector
*
* @tparam T
* @param list
*/
template <typename T>
static void printVector(vector<T> &list) {
cout << getVectorString(list) << '\n';
}
/**
* @brief Print a vector matrix
*
* @tparam T
* @param matrix
*/
template <typename T>
static void printVectorMatrix(vector<vector<T>> &matrix) {
cout << "[" << '\n';
for (vector<T> &list : matrix)
cout << " " + getVectorString(list) + "," << '\n';
cout << "]" << '\n';
}
/**
* @brief Print a linked list
*
* @param head
*/
static void printLinkedList(ListNode *head) {
vector<int> 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);
}
};

View File

@ -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<int> list) {
TreeNode *root = new TreeNode(list[0]);
queue<TreeNode*> 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;
}

View File

@ -0,0 +1,23 @@
/*
* File: PrintUtil.hpp
* Created Time: 2021-12-19
* Author: Krahets (krahets@163.com)
*/
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include "ListNode.hpp"
#include "TreeNode.hpp"
#include "PrintUtil.hpp"
using namespace std;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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 {

View File

@ -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.*;

View File

@ -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 {

View File

@ -1,3 +1,9 @@
/*
* File: hashing_search.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_searching;
import include.*;

View File

@ -1,3 +1,9 @@
/*
* File: linear_search.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_searching;
import include.*;

View File

@ -1,3 +1,9 @@
/*
* File: bubble_sort.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;

View File

@ -1,3 +1,9 @@
/*
* File: insertion_sort.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;

View File

@ -1,3 +1,9 @@
/*
* File: merge_sort.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;

View File

@ -1,3 +1,9 @@
/*
* File: quick_sort.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -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.*;

View File

@ -1,3 +1,9 @@
/*
* File: binary_tree.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_tree;
import include.*;

View File

@ -1,3 +1,9 @@
/*
* File: binary_tree_bfs.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_tree;
import include.*;

View File

@ -1,3 +1,9 @@
/*
* File: binary_tree_dfs.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package chapter_tree;
import include.*;

View File

@ -1,3 +1,9 @@
/*
* File: ListNode.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package include;
/**

View File

@ -1,3 +1,9 @@
/*
* File: PrintUtil.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package include;
import java.util.*;

View File

@ -1,3 +1,9 @@
/*
* File: TreeNode.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
package include;
import java.util.*;

View File

@ -0,0 +1,10 @@
'''
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 *

View File

@ -0,0 +1,10 @@
'''
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 *

View File

@ -0,0 +1,10 @@
'''
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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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 *

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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)
<p align="center"> Fig. 数据结构与算法的关系 </p>
!!! tip "约定俗成的习惯"
在实际讨论中,我们通常会将「数据结构与算法」简称为「算法」。例如,我们熟称的 LeetCode 算法题目,实际上同时考察了数据结构和算法两部分知识。

View File

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Some files were not shown because too many files have changed in this diff Show More