Merge branch 'krahets:master' into master
This commit is contained in:
commit
98df4a1bfe
12
README.md
12
README.md
@ -1,6 +1,6 @@
|
||||
<p align="center">
|
||||
<a href="https://www.hello-algo.com/">
|
||||
<img src="docs/index.assets/conceptual_rendering.png" width="230">
|
||||
<img src="https://www.hello-algo.com/index.assets/conceptual_rendering.png" width="230">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@ -15,7 +15,9 @@
|
||||
</br>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/index.assets/animation.gif" width="700">
|
||||
<img src="https://www.hello-algo.com/index.assets/animation.gif" width="400">
|
||||
<a> </a>
|
||||
<img src="https://www.hello-algo.com/index.assets/running_code.gif" width="400">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@ -29,7 +31,7 @@
|
||||
|
||||
## 关于本书
|
||||
|
||||
本书致力于达成以下目标:
|
||||
本书面向数据结构与算法初学者,致力于达成以下目标:
|
||||
|
||||
- 开源免费,所有同学都可在网上获取本书;
|
||||
- 新手友好,适合算法初学者自主学习入门;
|
||||
@ -56,10 +58,10 @@
|
||||
|
||||
## To-Dos
|
||||
|
||||
- [x] [代码翻译](https://github.com/krahets/hello-algo/issues/15)(JavaScript, TypeScript, C, C++, C#, ... 寻求大佬帮助)
|
||||
- [x] [代码翻译](https://github.com/krahets/hello-algo/issues/15):Java, C++, Python, Go, JavaScript 正在进行中,其他语言请求大佬挑大梁
|
||||
- [ ] 数据结构:散列表、堆(优先队列)、图
|
||||
- [ ] 算法:搜索与回溯、选择 / 堆排序、动态规划、贪心、分治
|
||||
|
||||
## License
|
||||
|
||||
The texts, codes, images, photos, and videos in this repository is licensed under [CC BY-NC-SA-4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).
|
||||
The texts, codes, images, photos, and videos in this repository are licensed under [CC BY-NC-SA-4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).
|
||||
|
||||
@ -34,14 +34,14 @@ public:
|
||||
int get(int index) {
|
||||
// 索引如果越界则抛出异常,下同
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
return nums[index];
|
||||
}
|
||||
|
||||
/* 更新元素 */
|
||||
void set(int index, int num) {
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
@ -58,7 +58,7 @@ public:
|
||||
/* 中间插入元素 */
|
||||
void insert(int index, int num) {
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (size() == capacity())
|
||||
extendCapacity();
|
||||
@ -72,15 +72,18 @@ public:
|
||||
}
|
||||
|
||||
/* 删除元素 */
|
||||
void remove(int index) {
|
||||
int remove(int index) {
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
int num = nums[index];
|
||||
// 索引 i 之后的元素都向前移动一位
|
||||
for (int j = index; j < size() - 1; j++) {
|
||||
nums[j] = nums[j + 1];
|
||||
}
|
||||
// 更新元素数量
|
||||
numsSize--;
|
||||
// 返回被删除元素
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 列表扩容 */
|
||||
|
||||
@ -40,7 +40,7 @@ int main() {
|
||||
cout << "目标元素 3 的索引 = " << index << endl;
|
||||
|
||||
/* 哈希查找(链表) */
|
||||
ListNode* head = vectorToLinkedList(nums);
|
||||
ListNode* head = vecToLinkedList(nums);
|
||||
// 初始化哈希表
|
||||
unordered_map<int, ListNode*> map1;
|
||||
while (head != nullptr) {
|
||||
|
||||
@ -42,7 +42,7 @@ int main() {
|
||||
cout << "目标元素 3 的索引 = " << index << endl;
|
||||
|
||||
/* 在链表中执行线性查找 */
|
||||
ListNode* head = vectorToLinkedList(nums);
|
||||
ListNode* head = vecToLinkedList(nums);
|
||||
ListNode* node = linearSearch(head, target);
|
||||
cout << "目标结点值 3 的对应结点对象为 " << node << endl;
|
||||
|
||||
|
||||
@ -6,3 +6,129 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
/* 基于环形数组实现的队列 */
|
||||
class ArrayQueue {
|
||||
private:
|
||||
int *nums; // 用于存储队列元素的数组
|
||||
int cap; // 队列容量
|
||||
int front = 0; // 头指针,指向队首
|
||||
int rear = 0; // 尾指针,指向队尾 + 1
|
||||
|
||||
public:
|
||||
ArrayQueue(int capacity) {
|
||||
// 初始化数组
|
||||
cap = capacity;
|
||||
nums = new int[capacity];
|
||||
}
|
||||
|
||||
/* 获取队列的容量 */
|
||||
int capacity() {
|
||||
return cap;
|
||||
}
|
||||
|
||||
/* 获取队列的长度 */
|
||||
int size() {
|
||||
// 由于将数组看作为环形,可能 rear < front ,因此需要取余数
|
||||
return (capacity() + rear - front) % capacity();
|
||||
}
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
bool empty() {
|
||||
return rear - front == 0;
|
||||
}
|
||||
|
||||
/* 入队 */
|
||||
void offer(int num) {
|
||||
if (size() == capacity()) {
|
||||
cout << "队列已满" << endl;
|
||||
return;
|
||||
}
|
||||
// 尾结点后添加 num
|
||||
nums[rear] = num;
|
||||
// 尾指针向后移动一位,越过尾部后返回到数组头部
|
||||
rear = (rear + 1) % capacity();
|
||||
}
|
||||
|
||||
/* 出队 */
|
||||
int poll() {
|
||||
int num = peek();
|
||||
// 队头指针向后移动一位,若越过尾部则返回到数组头部
|
||||
front = (front + 1) % capacity();
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 访问队首元素 */
|
||||
int peek() {
|
||||
// 删除头结点
|
||||
if (empty())
|
||||
throw out_of_range("队列为空");
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* 访问指定索引元素 */
|
||||
int get(int index) {
|
||||
if (index >= size())
|
||||
throw out_of_range("索引越界");
|
||||
return nums[(front + index) % capacity()];
|
||||
}
|
||||
|
||||
/* 将数组转化为 Vector 并返回 */
|
||||
vector<int> toVector() {
|
||||
int siz = size();
|
||||
int cap = capacity();
|
||||
// 仅转换有效长度范围内的列表元素
|
||||
vector<int> arr(siz);
|
||||
for (int i = 0, j = front; i < siz; i++, j++) {
|
||||
arr[i] = nums[j % cap];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化队列 */
|
||||
int capacity = 10;
|
||||
ArrayQueue* queue = new ArrayQueue(capacity);
|
||||
|
||||
/* 元素入队 */
|
||||
queue->offer(1);
|
||||
queue->offer(3);
|
||||
queue->offer(2);
|
||||
queue->offer(5);
|
||||
queue->offer(4);
|
||||
cout << "队列 queue = ";
|
||||
PrintUtil::printVector(queue->toVector());
|
||||
|
||||
/* 访问队首元素 */
|
||||
int peek = queue->peek();
|
||||
cout << "队首元素 peek = " << peek << endl;
|
||||
|
||||
/* 访问指定索引元素 */
|
||||
int num = queue->get(2);
|
||||
cout << "队列第 3 个元素为 num = " << num << endl;
|
||||
|
||||
/* 元素出队 */
|
||||
int poll = queue->poll();
|
||||
cout << "出队元素 poll = " << poll << ",出队后 queue = ";
|
||||
PrintUtil::printVector(queue->toVector());
|
||||
|
||||
/* 获取队列的长度 */
|
||||
int size = queue->size();
|
||||
cout << "队列长度 size = " << size << endl;
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
bool empty = queue->empty();
|
||||
cout << "队列是否为空 = " << empty << endl;
|
||||
|
||||
/* 测试环形数组 */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
queue->offer(i);
|
||||
queue->poll();
|
||||
cout << "第 " << i << " 轮入队 + 出队后 queue = ";
|
||||
PrintUtil::printVector(queue->toVector());
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -1,8 +1,90 @@
|
||||
/*
|
||||
* File: array_stack.cpp
|
||||
* Created Time: 2022-11-25
|
||||
* Author: Krahets (krahets@163.com)
|
||||
* Created Time: 2022-11-28
|
||||
* Author: qualifier1024 (2539244001@qq.com)
|
||||
*/
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
/* 基于数组实现的栈 */
|
||||
class ArrayStack {
|
||||
private:
|
||||
vector<int> stack;
|
||||
|
||||
public:
|
||||
/* 获取栈的长度 */
|
||||
int size() {
|
||||
return stack.size();
|
||||
}
|
||||
|
||||
/* 判断栈是否为空 */
|
||||
bool empty() {
|
||||
return stack.empty();
|
||||
}
|
||||
|
||||
/* 入栈 */
|
||||
void push(int num) {
|
||||
stack.push_back(num);
|
||||
}
|
||||
|
||||
/* 出栈 */
|
||||
int pop() {
|
||||
int oldTop = stack.back();
|
||||
stack.pop_back();
|
||||
return oldTop;
|
||||
}
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
int top() {
|
||||
return stack.back();
|
||||
}
|
||||
|
||||
/* 访问索引 index 处元素 */
|
||||
int get(int index) {
|
||||
return stack[index];
|
||||
}
|
||||
|
||||
/* 返回 Vector */
|
||||
vector<int> toVector() {
|
||||
return stack;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化栈 */
|
||||
ArrayStack* stack = new ArrayStack();
|
||||
|
||||
/* 元素入栈 */
|
||||
stack->push(1);
|
||||
stack->push(3);
|
||||
stack->push(2);
|
||||
stack->push(5);
|
||||
stack->push(4);
|
||||
cout << "栈 stack = ";
|
||||
PrintUtil::printVector(stack->toVector());
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
int top = stack->top();
|
||||
cout << "栈顶元素 top = " << top << endl;
|
||||
|
||||
/* 访问索引 index 处元素 */
|
||||
int num = stack->get(3);
|
||||
cout << "栈索引 3 处的元素为 num = " << num << endl;
|
||||
|
||||
/* 元素出栈 */
|
||||
int pop = stack->pop();
|
||||
cout << "出栈元素 pop = " << pop << ",出栈后 stack = ";
|
||||
PrintUtil::printVector(stack->toVector());
|
||||
|
||||
/* 获取栈的长度 */
|
||||
int size = stack->size();
|
||||
cout << "栈的长度 size = " << size << endl;
|
||||
|
||||
/* 判断是否为空 */
|
||||
bool empty = stack->empty();
|
||||
cout << "栈是否为空 = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -6,3 +6,42 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化双向队列 */
|
||||
deque<int> deque;
|
||||
|
||||
/* 元素入队 */
|
||||
deque.push_back(2);
|
||||
deque.push_back(5);
|
||||
deque.push_back(4);
|
||||
deque.push_front(3);
|
||||
deque.push_front(1);
|
||||
cout << "双向队列 deque = ";
|
||||
PrintUtil::printDeque(deque);
|
||||
|
||||
/* 访问元素 */
|
||||
int front = deque.front();
|
||||
cout << "队首元素 front = " << front << endl;
|
||||
int back = deque.back();
|
||||
cout << "队尾元素 back = " << back << endl;
|
||||
|
||||
/* 元素出队 */
|
||||
deque.pop_front();
|
||||
cout << "队首出队元素 popFront = " << front << ",队首出队后 deque = ";
|
||||
PrintUtil::printDeque(deque);
|
||||
deque.pop_back();
|
||||
cout << "队尾出队元素 popLast = " << back << ",队尾出队后 deque = ";
|
||||
PrintUtil::printDeque(deque);
|
||||
|
||||
/* 获取双向队列的长度 */
|
||||
int size = deque.size();
|
||||
cout << "双向队列长度 size = " << size << endl;
|
||||
|
||||
/* 判断双向队列是否为空 */
|
||||
bool empty = deque.empty();
|
||||
cout << "双向队列是否为空 = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -6,3 +6,105 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
/* 基于链表实现的队列 */
|
||||
class LinkedListQueue {
|
||||
private:
|
||||
ListNode *front, *rear; // 头结点 front ,尾结点 rear
|
||||
int queSize;
|
||||
|
||||
public:
|
||||
LinkedListQueue() {
|
||||
front = nullptr;
|
||||
rear = nullptr;
|
||||
queSize = 0;
|
||||
}
|
||||
|
||||
/* 获取队列的长度 */
|
||||
int size() {
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
bool empty() {
|
||||
return queSize == 0;
|
||||
}
|
||||
|
||||
/* 入队 */
|
||||
void offer(int num) {
|
||||
// 尾结点后添加 num
|
||||
ListNode* node = new ListNode(num);
|
||||
// 如果队列为空,则令头、尾结点都指向该结点
|
||||
if (front == nullptr) {
|
||||
front = node;
|
||||
rear = node;
|
||||
}
|
||||
// 如果队列不为空,则将该结点添加到尾结点后
|
||||
else {
|
||||
rear->next = node;
|
||||
rear = node;
|
||||
}
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* 出队 */
|
||||
int poll() {
|
||||
int num = peek();
|
||||
// 删除头结点
|
||||
front = front->next;
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 访问队首元素 */
|
||||
int peek() {
|
||||
if (size() == 0)
|
||||
throw out_of_range("队列为空");
|
||||
return front->val;
|
||||
}
|
||||
|
||||
/* 将链表转化为 Vector 并返回 */
|
||||
vector<int> toVector() {
|
||||
ListNode* node = front;
|
||||
vector<int> res(size());
|
||||
for (int i = 0; i < res.size(); i++) {
|
||||
res[i] = node->val;
|
||||
node = node->next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化队列 */
|
||||
LinkedListQueue* queue = new LinkedListQueue();
|
||||
|
||||
/* 元素入队 */
|
||||
queue->offer(1);
|
||||
queue->offer(3);
|
||||
queue->offer(2);
|
||||
queue->offer(5);
|
||||
queue->offer(4);
|
||||
cout << "队列 queue = ";
|
||||
PrintUtil::printVector(queue->toVector());
|
||||
|
||||
/* 访问队首元素 */
|
||||
int peek = queue->peek();
|
||||
cout << "队首元素 peek = " << peek << endl;
|
||||
|
||||
/* 元素出队 */
|
||||
int poll = queue->poll();
|
||||
cout << "出队元素 poll = " << poll << ",出队后 queue = ";
|
||||
PrintUtil::printVector(queue->toVector());
|
||||
|
||||
/* 获取队列的长度 */
|
||||
int size = queue->size();
|
||||
cout << "队列长度 size = " << size << endl;
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
bool empty = queue->empty();
|
||||
cout << "队列是否为空 = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -1,8 +1,99 @@
|
||||
/*
|
||||
* File: linkedlist_stack.cpp
|
||||
* Created Time: 2022-11-25
|
||||
* Author: Krahets (krahets@163.com)
|
||||
* Created Time: 2022-11-28
|
||||
* Author: qualifier1024 (2539244001@qq.com)
|
||||
*/
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
/* 基于链表实现的栈 */
|
||||
class LinkedListStack {
|
||||
private:
|
||||
ListNode* stackTop; // 将头结点作为栈顶
|
||||
int stkSize; // 栈的长度
|
||||
|
||||
public:
|
||||
LinkedListStack() {
|
||||
stackTop = nullptr;
|
||||
stkSize = 0;
|
||||
}
|
||||
|
||||
/* 获取栈的长度 */
|
||||
int size() {
|
||||
return stkSize;
|
||||
}
|
||||
|
||||
/* 判断栈是否为空 */
|
||||
bool empty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* 入栈 */
|
||||
void push(int num) {
|
||||
ListNode* node = new ListNode(num);
|
||||
node->next = stackTop;
|
||||
stackTop = node;
|
||||
stkSize++;
|
||||
}
|
||||
|
||||
/* 出栈 */
|
||||
int pop() {
|
||||
int num = top();
|
||||
stackTop = stackTop->next;
|
||||
stkSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
int top() {
|
||||
if (size() == 0)
|
||||
throw out_of_range("栈为空");
|
||||
return stackTop->val;
|
||||
}
|
||||
|
||||
/* 将 List 转化为 Array 并返回 */
|
||||
vector<int> toVector() {
|
||||
ListNode* node = stackTop;
|
||||
vector<int> res(size());
|
||||
for (int i = res.size() - 1; i >= 0; i--) {
|
||||
res[i] = node->val;
|
||||
node = node->next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化栈 */
|
||||
LinkedListStack* stack = new LinkedListStack();
|
||||
|
||||
/* 元素入栈 */
|
||||
stack->push(1);
|
||||
stack->push(3);
|
||||
stack->push(2);
|
||||
stack->push(5);
|
||||
stack->push(4);
|
||||
cout << "栈 stack = ";
|
||||
PrintUtil::printVector(stack->toVector());
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
int top = stack->top();
|
||||
cout << "栈顶元素 top = " << top << endl;
|
||||
|
||||
/* 元素出栈 */
|
||||
int pop = stack->pop();
|
||||
cout << "出栈元素 pop = " << pop << ",出栈后 stack = ";
|
||||
PrintUtil::printVector(stack->toVector());
|
||||
|
||||
/* 获取栈的长度 */
|
||||
int size = stack->size();
|
||||
cout << "栈的长度 size = " << size << endl;
|
||||
|
||||
/* 判断是否为空 */
|
||||
bool empty = stack->empty();
|
||||
cout << "栈是否为空 = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -1,8 +1,42 @@
|
||||
/*
|
||||
* File: queue.cpp
|
||||
* Created Time: 2022-11-25
|
||||
* Author: Krahets (krahets@163.com)
|
||||
* Created Time: 2022-11-28
|
||||
* Author: qualifier1024 (2539244001@qq.com)
|
||||
*/
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main(){
|
||||
/* 初始化队列 */
|
||||
queue<int> queue;
|
||||
|
||||
/* 元素入队 */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
queue.push(5);
|
||||
queue.push(4);
|
||||
cout << "队列 queue = ";
|
||||
PrintUtil::printQueue(queue);
|
||||
|
||||
/* 访问队首元素 */
|
||||
int front = queue.front();
|
||||
cout << "队首元素 front = " << front << endl;
|
||||
|
||||
/* 元素出队 */
|
||||
queue.pop();
|
||||
cout << "出队元素 front = " << front << ",出队后 queue = ";
|
||||
PrintUtil::printQueue(queue);
|
||||
|
||||
/* 获取队列的长度 */
|
||||
int size = queue.size();
|
||||
cout << "队列长度 size = " << size << endl;
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
bool empty = queue.empty();
|
||||
cout << "队列是否为空 = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -1,8 +1,42 @@
|
||||
/*
|
||||
* File: stack.cpp
|
||||
* Created Time: 2022-11-25
|
||||
* Author: Krahets (krahets@163.com)
|
||||
* Created Time: 2022-11-28
|
||||
* Author: qualifier1024 (2539244001@qq.com)
|
||||
*/
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化栈 */
|
||||
stack<int> stack;
|
||||
|
||||
/* 元素入栈 */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
cout << "栈 stack = ";
|
||||
PrintUtil::printStack(stack);
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
int top = stack.top();
|
||||
cout << "栈顶元素 top = " << top << endl;
|
||||
|
||||
/* 元素出栈 */
|
||||
stack.pop();
|
||||
cout << "出栈元素 pop = " << top << ",出栈后 stack = ";
|
||||
PrintUtil::printStack(stack);
|
||||
|
||||
/* 获取栈的长度 */
|
||||
int size = stack.size();
|
||||
cout << "栈的长度 size = " << size << endl;
|
||||
|
||||
/* 判断是否为空 */
|
||||
bool empty = stack.empty();
|
||||
cout << "栈是否为空 = " << empty << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -6,3 +6,149 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
/* 二叉搜索树 */
|
||||
class BinarySearchTree {
|
||||
private:
|
||||
TreeNode* root;
|
||||
|
||||
public:
|
||||
BinarySearchTree(vector<int> nums) {
|
||||
sort(nums.begin(), nums.end()); // 排序数组
|
||||
root = buildTree(nums, 0, nums.size() - 1); // 构建二叉搜索树
|
||||
}
|
||||
|
||||
/* 获取二叉树根结点 */
|
||||
TreeNode* getRoot() {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 构建二叉搜索树 */
|
||||
TreeNode* buildTree(vector<int> nums, int i, int j) {
|
||||
if (i > j) return nullptr;
|
||||
// 将数组中间结点作为根结点
|
||||
int mid = (i + j) / 2;
|
||||
TreeNode* root = new TreeNode(nums[mid]);
|
||||
// 递归建立左子树和右子树
|
||||
root->left = buildTree(nums, i, mid - 1);
|
||||
root->right = buildTree(nums, mid + 1, j);
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 查找结点 */
|
||||
TreeNode* search(int num) {
|
||||
TreeNode* cur = root;
|
||||
// 循环查找,越过叶结点后跳出
|
||||
while (cur != nullptr) {
|
||||
// 目标结点在 root 的右子树中
|
||||
if (cur->val < num) cur = cur->right;
|
||||
// 目标结点在 root 的左子树中
|
||||
else if (cur->val > num) cur = cur->left;
|
||||
// 找到目标结点,跳出循环
|
||||
else break;
|
||||
}
|
||||
// 返回目标结点
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* 插入结点 */
|
||||
TreeNode* insert(int num) {
|
||||
// 若树为空,直接提前返回
|
||||
if (root == nullptr) return nullptr;
|
||||
TreeNode *cur = root, *pre = nullptr;
|
||||
// 循环查找,越过叶结点后跳出
|
||||
while (cur != nullptr) {
|
||||
// 找到重复结点,直接返回
|
||||
if (cur->val == num) return nullptr;
|
||||
pre = cur;
|
||||
// 插入位置在 root 的右子树中
|
||||
if (cur->val < num) cur = cur->right;
|
||||
// 插入位置在 root 的左子树中
|
||||
else cur = cur->left;
|
||||
}
|
||||
// 插入结点 val
|
||||
TreeNode* node = new TreeNode(num);
|
||||
if (pre->val < num) pre->right = node;
|
||||
else pre->left = node;
|
||||
return node;
|
||||
}
|
||||
|
||||
/* 删除结点 */
|
||||
TreeNode* remove(int num) {
|
||||
// 若树为空,直接提前返回
|
||||
if (root == nullptr) return nullptr;
|
||||
TreeNode *cur = root, *pre = nullptr;
|
||||
// 循环查找,越过叶结点后跳出
|
||||
while (cur != nullptr) {
|
||||
// 找到待删除结点,跳出循环
|
||||
if (cur->val == num) break;
|
||||
pre = cur;
|
||||
// 待删除结点在 root 的右子树中
|
||||
if (cur->val < num) cur = cur->right;
|
||||
// 待删除结点在 root 的左子树中
|
||||
else cur = cur->left;
|
||||
}
|
||||
// 若无待删除结点,则直接返回
|
||||
if (cur == nullptr) return nullptr;
|
||||
// 子结点数量 = 0 or 1
|
||||
if (cur->left == nullptr || cur->right == nullptr) {
|
||||
// 当子结点数量 = 0 / 1 时, child = nullptr / 该子结点
|
||||
TreeNode* child = cur->left != nullptr ? cur->left : cur->right;
|
||||
// 删除结点 cur
|
||||
if (pre->left == cur) pre->left = child;
|
||||
else pre->right = child;
|
||||
}
|
||||
// 子结点数量 = 2
|
||||
else {
|
||||
// 获取中序遍历中 cur 的下一个结点
|
||||
TreeNode* nex = min(cur->right);
|
||||
int tmp = nex->val;
|
||||
// 递归删除结点 nex
|
||||
remove(nex->val);
|
||||
// 将 nex 的值复制给 cur
|
||||
cur->val = tmp;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* 获取最小结点 */
|
||||
TreeNode* min(TreeNode* root) {
|
||||
if (root == nullptr) return root;
|
||||
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
||||
while (root->left != nullptr) {
|
||||
root = root->left;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化二叉搜索树 */
|
||||
vector<int> nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
|
||||
BinarySearchTree* bst = new BinarySearchTree(nums);
|
||||
cout << endl << "初始化的二叉树为\n" << endl;
|
||||
PrintUtil::printTree(bst->getRoot());
|
||||
|
||||
/* 查找结点 */
|
||||
TreeNode* node = bst->search(5);
|
||||
cout << endl << "查找到的结点对象为 " << node << ",结点值 = " << node->val << endl;
|
||||
|
||||
/* 插入结点 */
|
||||
node = bst->insert(16);
|
||||
cout << endl << "插入结点 16 后,二叉树为\n" << endl;
|
||||
PrintUtil::printTree(bst->getRoot());
|
||||
|
||||
/* 删除结点 */
|
||||
bst->remove(1);
|
||||
cout << endl << "删除结点 1 后,二叉树为\n" << endl;
|
||||
PrintUtil::printTree(bst->getRoot());
|
||||
bst->remove(2);
|
||||
cout << endl << "删除结点 2 后,二叉树为\n" << endl;
|
||||
PrintUtil::printTree(bst->getRoot());
|
||||
bst->remove(4);
|
||||
cout << endl << "删除结点 4 后,二叉树为\n" << endl;
|
||||
PrintUtil::printTree(bst->getRoot());
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -6,3 +6,35 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化二叉树 */
|
||||
// 初始化结点
|
||||
TreeNode* n1 = new TreeNode(1);
|
||||
TreeNode* n2 = new TreeNode(2);
|
||||
TreeNode* n3 = new TreeNode(3);
|
||||
TreeNode* n4 = new TreeNode(4);
|
||||
TreeNode* n5 = new TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1->left = n2;
|
||||
n1->right = n3;
|
||||
n2->left = n4;
|
||||
n2->right = n5;
|
||||
cout << endl << "初始化二叉树\n" << endl;
|
||||
PrintUtil::printTree(n1);
|
||||
|
||||
/* 插入与删除结点 */
|
||||
TreeNode* P = new TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入结点 P
|
||||
n1->left = P;
|
||||
P->left = n2;
|
||||
cout << endl << "插入结点 P 后\n" << endl;
|
||||
PrintUtil::printTree(n1);
|
||||
// 删除结点 P
|
||||
n1->left = n2;
|
||||
cout << endl << "删除结点 P 后\n" << endl;
|
||||
PrintUtil::printTree(n1);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -6,3 +6,39 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
/* 层序遍历 */
|
||||
vector<int> hierOrder(TreeNode* root) {
|
||||
// 初始化队列,加入根结点
|
||||
queue<TreeNode*> queue;
|
||||
queue.push(root);
|
||||
// 初始化一个列表,用于保存遍历序列
|
||||
vector<int> vec;
|
||||
while (!queue.empty()) {
|
||||
TreeNode* node = queue.front();
|
||||
queue.pop(); // 队列出队
|
||||
vec.push_back(node->val); // 保存结点
|
||||
if (node->left != nullptr)
|
||||
queue.push(node->left); // 左子结点入队
|
||||
if (node->right != nullptr)
|
||||
queue.push(node->right); // 右子结点入队
|
||||
}
|
||||
return vec;
|
||||
}
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
TreeNode* root = vecToTree(vector<int>
|
||||
{ 1, 2, 3, 4, 5, 6, 7, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX });
|
||||
cout << endl << "初始化二叉树\n" << endl;
|
||||
PrintUtil::printTree(root);
|
||||
|
||||
/* 层序遍历 */
|
||||
vector<int> vec = hierOrder(root);
|
||||
cout << endl << "层序遍历的结点打印序列 = ";
|
||||
PrintUtil::printVector(vec);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -6,3 +6,63 @@
|
||||
|
||||
#include "../include/include.hpp"
|
||||
|
||||
// 初始化列表,用于存储遍历序列
|
||||
vector<int> vec;
|
||||
|
||||
/* 前序遍历 */
|
||||
void preOrder(TreeNode* root) {
|
||||
if (root == nullptr) return;
|
||||
// 访问优先级:根结点 -> 左子树 -> 右子树
|
||||
vec.push_back(root->val);
|
||||
preOrder(root->left);
|
||||
preOrder(root->right);
|
||||
}
|
||||
|
||||
/* 中序遍历 */
|
||||
void inOrder(TreeNode* root) {
|
||||
if (root == nullptr) return;
|
||||
// 访问优先级:左子树 -> 根结点 -> 右子树
|
||||
inOrder(root->left);
|
||||
vec.push_back(root->val);
|
||||
inOrder(root->right);
|
||||
}
|
||||
|
||||
/* 后序遍历 */
|
||||
void postOrder(TreeNode* root) {
|
||||
if (root == nullptr) return;
|
||||
// 访问优先级:左子树 -> 右子树 -> 根结点
|
||||
postOrder(root->left);
|
||||
postOrder(root->right);
|
||||
vec.push_back(root->val);
|
||||
}
|
||||
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
TreeNode* root = vecToTree(vector<int>
|
||||
{ 1, 2, 3, 4, 5, 6, 7, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX});
|
||||
cout << endl << "初始化二叉树\n" << endl;
|
||||
PrintUtil::printTree(root);
|
||||
|
||||
/* 前序遍历 */
|
||||
vec.clear();
|
||||
preOrder(root);
|
||||
cout << endl << "前序遍历的结点打印序列 = ";
|
||||
PrintUtil::printVector(vec);
|
||||
|
||||
/* 中序遍历 */
|
||||
vec.clear();
|
||||
inOrder(root);
|
||||
cout << endl << "中序遍历的结点打印序列 = ";
|
||||
PrintUtil::printVector(vec);
|
||||
|
||||
/* 后序遍历 */
|
||||
vec.clear();
|
||||
postOrder(root);
|
||||
cout << endl << "后序遍历的结点打印序列 = ";
|
||||
PrintUtil::printVector(vec);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -25,7 +25,7 @@ struct ListNode {
|
||||
* @param list
|
||||
* @return ListNode*
|
||||
*/
|
||||
ListNode* vectorToLinkedList(vector<int>& list) {
|
||||
ListNode* vecToLinkedList(vector<int> list) {
|
||||
ListNode *dum = new ListNode(0);
|
||||
ListNode *head = dum;
|
||||
for (int val : list) {
|
||||
|
||||
@ -102,7 +102,7 @@ class PrintUtil {
|
||||
* @param list
|
||||
*/
|
||||
template <typename T>
|
||||
static void printVector(vector<T> &list) {
|
||||
static void printVector(vector<T> list) {
|
||||
cout << getVectorString(list) << '\n';
|
||||
}
|
||||
|
||||
@ -210,4 +210,71 @@ class PrintUtil {
|
||||
|
||||
printTree(root->left, trunk, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Print a stack
|
||||
*
|
||||
* @tparam T
|
||||
* @param stk
|
||||
*/
|
||||
template <typename T>
|
||||
static void printStack(stack<T> stk) {
|
||||
// Reverse the input stack
|
||||
stack<T> tmp;
|
||||
while(!stk.empty()) {
|
||||
tmp.push(stk.top());
|
||||
stk.pop();
|
||||
}
|
||||
// Generate the string to print
|
||||
ostringstream s;
|
||||
bool flag = true;
|
||||
while(!tmp.empty()) {
|
||||
if (flag) {
|
||||
s << tmp.top();
|
||||
flag = false;
|
||||
}
|
||||
else s << ", " << tmp.top();
|
||||
tmp.pop();
|
||||
}
|
||||
cout << "[" + s.str() + "]" << '\n';
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief
|
||||
*
|
||||
* @tparam T
|
||||
* @param queue
|
||||
*/
|
||||
template <typename T>
|
||||
static void printQueue(queue<T> queue)
|
||||
{
|
||||
// Generate the string to print
|
||||
ostringstream s;
|
||||
bool flag = true;
|
||||
while(!queue.empty()) {
|
||||
if (flag) {
|
||||
s << queue.front();
|
||||
flag = false;
|
||||
}
|
||||
else s << ", " << queue.front();
|
||||
queue.pop();
|
||||
}
|
||||
cout << "[" + s.str() + "]" << '\n';
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static void printDeque(deque<T> deque) {
|
||||
// Generate the string to print
|
||||
ostringstream s;
|
||||
bool flag = true;
|
||||
while(!deque.empty()) {
|
||||
if (flag) {
|
||||
s << deque.front();
|
||||
flag = false;
|
||||
}
|
||||
else s << ", " << deque.front();
|
||||
deque.pop_front();
|
||||
}
|
||||
cout << "[" + s.str() + "]" << '\n';
|
||||
}
|
||||
};
|
||||
|
||||
@ -23,25 +23,28 @@ struct TreeNode {
|
||||
* @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();
|
||||
TreeNode *vecToTree(vector<int> list) {
|
||||
if (list.empty()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto *root = new TreeNode(list[0]);
|
||||
queue<TreeNode *> que;
|
||||
size_t n = list.size(), index = 1;
|
||||
while (index < n) {
|
||||
auto node = que.front();
|
||||
que.pop();
|
||||
if(list[i] != INT_MAX) {
|
||||
node->left = new TreeNode(list[i]);
|
||||
|
||||
if (index < n) {
|
||||
node->left = new TreeNode(list[index++]);
|
||||
que.emplace(node->left);
|
||||
}
|
||||
i++;
|
||||
if(list[i] != INT_MAX) {
|
||||
node->right = new TreeNode(list[i]);
|
||||
if (index < n) {
|
||||
node->right = new TreeNode(list[index++]);
|
||||
que.emplace(node->right);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
@ -52,7 +55,7 @@ TreeNode* vectorToTree(vector<int>& list) {
|
||||
* @param val
|
||||
* @return TreeNode*
|
||||
*/
|
||||
TreeNode* getTreeNode(TreeNode *root, int val) {
|
||||
TreeNode *getTreeNode(TreeNode *root, int val) {
|
||||
if (root == nullptr)
|
||||
return nullptr;
|
||||
if (root->val == val)
|
||||
|
||||
@ -9,6 +9,7 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <list>
|
||||
#include <stack>
|
||||
#include <queue>
|
||||
#include <deque>
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
package chapter_computational_complexity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@ -16,8 +17,8 @@ func TestTwoSum(t *testing.T) {
|
||||
// ====== Driver Code ======
|
||||
// 方法一:暴力解法
|
||||
res := twoSumBruteForce(nums, target)
|
||||
t.Log("方法一 res =", res)
|
||||
fmt.Println("方法一 res =", res)
|
||||
// 方法二:哈希表
|
||||
res = twoSumHashTable(nums, target)
|
||||
t.Log("方法二 res =", res)
|
||||
fmt.Println("方法二 res =", res)
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
package chapter_searching
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
@ -16,10 +17,10 @@ func TestLinearSearch(t *testing.T) {
|
||||
|
||||
// 在数组中执行线性查找
|
||||
index := linerSearchArray(nums, target)
|
||||
t.Log("目标元素 3 的索引 =", index)
|
||||
fmt.Println("目标元素 3 的索引 =", index)
|
||||
|
||||
// 在链表中执行线性查找
|
||||
head := ArrayToLinkedList(nums)
|
||||
node := linerSearchLinkedList(head, target)
|
||||
t.Log("目标结点值 3 的对应结点对象为", node)
|
||||
fmt.Println("目标结点值 3 的对应结点对象为", node)
|
||||
}
|
||||
|
||||
71
codes/go/chapter_stack_and_queue/array_queue.go
Normal file
71
codes/go/chapter_stack_and_queue/array_queue.go
Normal file
@ -0,0 +1,71 @@
|
||||
// File: array_queue.go
|
||||
// Created Time: 2022-11-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
/* 基于环形数组实现的队列 */
|
||||
type ArrayQueue struct {
|
||||
data []int // 用于存储队列元素的数组
|
||||
capacity int // 队列容量(即最多容量的元素个数)
|
||||
front int // 头指针,指向队首
|
||||
rear int // 尾指针,指向队尾 + 1
|
||||
}
|
||||
|
||||
// NewArrayQueue 基于环形数组实现的队列
|
||||
func NewArrayQueue(capacity int) *ArrayQueue {
|
||||
return &ArrayQueue{
|
||||
data: make([]int, capacity),
|
||||
capacity: capacity,
|
||||
front: 0,
|
||||
rear: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Size 获取队列的长度
|
||||
func (q *ArrayQueue) Size() int {
|
||||
size := (q.capacity + q.rear - q.front) % q.capacity
|
||||
return size
|
||||
}
|
||||
|
||||
// IsEmpty 判断队列是否为空
|
||||
func (q *ArrayQueue) IsEmpty() bool {
|
||||
return q.rear-q.front == 0
|
||||
}
|
||||
|
||||
// Offer 入队
|
||||
func (q *ArrayQueue) Offer(v int) {
|
||||
// 当 rear == capacity 表示队列已满
|
||||
if q.Size() == q.capacity {
|
||||
return
|
||||
}
|
||||
// 尾结点后添加
|
||||
q.data[q.rear] = v
|
||||
// 尾指针向后移动一位,越过尾部后返回到数组头部
|
||||
q.rear = (q.rear + 1) % q.capacity
|
||||
}
|
||||
|
||||
// Poll 出队
|
||||
func (q *ArrayQueue) Poll() any {
|
||||
if q.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
v := q.data[q.front]
|
||||
// 队头指针向后移动一位,若越过尾部则返回到数组头部
|
||||
q.front = (q.front + 1) % q.capacity
|
||||
return v
|
||||
}
|
||||
|
||||
// Peek 访问队首元素
|
||||
func (q *ArrayQueue) Peek() any {
|
||||
if q.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
v := q.data[q.front]
|
||||
return v
|
||||
}
|
||||
|
||||
// 获取 Slice 用于打印
|
||||
func (s *ArrayQueue) toSlice() []int {
|
||||
return s.data[s.front:s.rear]
|
||||
}
|
||||
58
codes/go/chapter_stack_and_queue/array_stack.go
Normal file
58
codes/go/chapter_stack_and_queue/array_stack.go
Normal file
@ -0,0 +1,58 @@
|
||||
// File: array_stack.go
|
||||
// Created Time: 2022-11-26
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
/* 基于数组实现的栈 */
|
||||
type ArrayStack struct {
|
||||
data []int // 数据
|
||||
}
|
||||
|
||||
func NewArrayStack() *ArrayStack {
|
||||
return &ArrayStack{
|
||||
// 设置栈的长度为 0,容量为 16
|
||||
data: make([]int, 0, 16),
|
||||
}
|
||||
}
|
||||
|
||||
// Size 栈的长度
|
||||
func (s *ArrayStack) Size() int {
|
||||
return len(s.data)
|
||||
}
|
||||
|
||||
// IsEmpty 栈是否为空
|
||||
func (s *ArrayStack) IsEmpty() bool {
|
||||
return s.Size() == 0
|
||||
}
|
||||
|
||||
// Push 入栈
|
||||
func (s *ArrayStack) Push(v int) {
|
||||
// 切片会自动扩容
|
||||
s.data = append(s.data, v)
|
||||
}
|
||||
|
||||
// Pop 出栈
|
||||
func (s *ArrayStack) Pop() any {
|
||||
// 弹出栈前,先判断是否为空
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
val := s.Peek()
|
||||
s.data = s.data[:len(s.data)-1]
|
||||
return val
|
||||
}
|
||||
|
||||
// Peek 获取栈顶元素
|
||||
func (s *ArrayStack) Peek() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
val := s.data[len(s.data)-1]
|
||||
return val
|
||||
}
|
||||
|
||||
// 获取 Slice 用于打印
|
||||
func (s *ArrayStack) toSlice() []int {
|
||||
return s.data
|
||||
}
|
||||
98
codes/go/chapter_stack_and_queue/deque_test.go
Normal file
98
codes/go/chapter_stack_and_queue/deque_test.go
Normal file
@ -0,0 +1,98 @@
|
||||
// File: deque_test.go
|
||||
// Created Time: 2022-11-29
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestDeque(t *testing.T) {
|
||||
/* 初始化双向队列 */
|
||||
// 在 Go 中,将 list 作为双向队列使用
|
||||
deque := list.New()
|
||||
|
||||
/* 元素入队 */
|
||||
deque.PushBack(2)
|
||||
deque.PushBack(5)
|
||||
deque.PushBack(4)
|
||||
deque.PushFront(3)
|
||||
deque.PushFront(1)
|
||||
fmt.Print("双向队列 deque = ")
|
||||
PrintList(deque)
|
||||
|
||||
/* 访问元素 */
|
||||
front := deque.Front()
|
||||
fmt.Println("队首元素 front =", front.Value)
|
||||
rear := deque.Back()
|
||||
fmt.Println("队尾元素 rear =", rear.Value)
|
||||
|
||||
/* 元素出队 */
|
||||
deque.Remove(front)
|
||||
fmt.Print("队首出队元素 front = ", front.Value, ",队首出队后 deque = ")
|
||||
PrintList(deque)
|
||||
deque.Remove(rear)
|
||||
fmt.Print("队尾出队元素 rear = ", rear.Value, ",队尾出队后 deque = ")
|
||||
PrintList(deque)
|
||||
|
||||
/* 获取双向队列的长度 */
|
||||
size := deque.Len()
|
||||
fmt.Println("双向队列长度 size =", size)
|
||||
|
||||
/* 判断双向队列是否为空 */
|
||||
isEmpty := deque.Len() == 0
|
||||
fmt.Println("双向队列是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
func TestLinkedListDeque(t *testing.T) {
|
||||
// 初始化队列
|
||||
deque := NewLinkedListDeque()
|
||||
|
||||
// 元素入队
|
||||
deque.OfferLast(2)
|
||||
deque.OfferLast(5)
|
||||
deque.OfferLast(4)
|
||||
deque.OfferFirst(3)
|
||||
deque.OfferFirst(1)
|
||||
fmt.Print("队列 deque = ")
|
||||
PrintList(deque.toList())
|
||||
|
||||
// 访问队首元素
|
||||
front := deque.PeekFirst()
|
||||
fmt.Println("队首元素 front =", front)
|
||||
rear := deque.PeekLast()
|
||||
fmt.Println("队尾元素 rear =", rear)
|
||||
|
||||
// 元素出队
|
||||
pollFirst := deque.PollFirst()
|
||||
fmt.Print("队首出队元素 pollFirst = ", pollFirst, ",队首出队后 deque = ")
|
||||
PrintList(deque.toList())
|
||||
pollLast := deque.PollLast()
|
||||
fmt.Print("队尾出队元素 pollLast = ", pollLast, ",队尾出队后 deque = ")
|
||||
PrintList(deque.toList())
|
||||
|
||||
// 获取队的长度
|
||||
size := deque.Size()
|
||||
fmt.Println("队的长度 size =", size)
|
||||
|
||||
// 判断是否为空
|
||||
isEmpty := deque.IsEmpty()
|
||||
fmt.Println("队是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
// BenchmarkArrayQueue 67.92 ns/op in Mac M1 Pro
|
||||
func BenchmarkLinkedListDeque(b *testing.B) {
|
||||
stack := NewLinkedListDeque()
|
||||
// use b.N for looping
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.OfferLast(777)
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.PollFirst()
|
||||
}
|
||||
}
|
||||
84
codes/go/chapter_stack_and_queue/linkedlist_deque.go
Normal file
84
codes/go/chapter_stack_and_queue/linkedlist_deque.go
Normal file
@ -0,0 +1,84 @@
|
||||
// File: linkedlist_deque.go
|
||||
// Created Time: 2022-11-29
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
)
|
||||
|
||||
// LinkedListDeque 基于链表实现的双端队列, 使用内置包 list 来实现栈
|
||||
type LinkedListDeque struct {
|
||||
data *list.List
|
||||
}
|
||||
|
||||
// NewLinkedListDeque 初始化双端队列
|
||||
func NewLinkedListDeque() *LinkedListDeque {
|
||||
return &LinkedListDeque{
|
||||
data: list.New(),
|
||||
}
|
||||
}
|
||||
|
||||
// OfferFirst 队首元素入队
|
||||
func (s *LinkedListDeque) OfferFirst(value any) {
|
||||
s.data.PushFront(value)
|
||||
}
|
||||
|
||||
// OfferLast 队尾元素入队
|
||||
func (s *LinkedListDeque) OfferLast(value any) {
|
||||
s.data.PushBack(value)
|
||||
}
|
||||
|
||||
// PollFirst 队首元素出队
|
||||
func (s *LinkedListDeque) PollFirst() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Front()
|
||||
s.data.Remove(e)
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// PollLast 队尾元素出队
|
||||
func (s *LinkedListDeque) PollLast() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Back()
|
||||
s.data.Remove(e)
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// PeekFirst 访问队首元素
|
||||
func (s *LinkedListDeque) PeekFirst() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Front()
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// PeekLast 访问队尾元素
|
||||
func (s *LinkedListDeque) PeekLast() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Back()
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// Size 获取队列的长度
|
||||
func (s *LinkedListDeque) Size() int {
|
||||
return s.data.Len()
|
||||
}
|
||||
|
||||
// IsEmpty 判断队列是否为空
|
||||
func (s *LinkedListDeque) IsEmpty() bool {
|
||||
return s.data.Len() == 0
|
||||
}
|
||||
|
||||
// 获取 List 用于打印
|
||||
func (s *LinkedListDeque) toList() *list.List {
|
||||
return s.data
|
||||
}
|
||||
61
codes/go/chapter_stack_and_queue/linkedlist_queue.go
Normal file
61
codes/go/chapter_stack_and_queue/linkedlist_queue.go
Normal file
@ -0,0 +1,61 @@
|
||||
// File: linkedlist_queue.go
|
||||
// Created Time: 2022-11-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
)
|
||||
|
||||
/* 基于链表实现的队列 */
|
||||
type LinkedListQueue struct {
|
||||
// 使用内置包 list 来实现队列
|
||||
data *list.List
|
||||
}
|
||||
|
||||
// NewLinkedListQueue 初始化链表
|
||||
func NewLinkedListQueue() *LinkedListQueue {
|
||||
return &LinkedListQueue{
|
||||
data: list.New(),
|
||||
}
|
||||
}
|
||||
|
||||
// Offer 入队
|
||||
func (s *LinkedListQueue) Offer(value any) {
|
||||
s.data.PushBack(value)
|
||||
}
|
||||
|
||||
// Poll 出队
|
||||
func (s *LinkedListQueue) Poll() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Front()
|
||||
s.data.Remove(e)
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// Peek 访问队首元素
|
||||
func (s *LinkedListQueue) Peek() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Front()
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// Size 获取队列的长度
|
||||
func (s *LinkedListQueue) Size() int {
|
||||
return s.data.Len()
|
||||
}
|
||||
|
||||
// IsEmpty 判断队列是否为空
|
||||
func (s *LinkedListQueue) IsEmpty() bool {
|
||||
return s.data.Len() == 0
|
||||
}
|
||||
|
||||
// 获取 List 用于打印
|
||||
func (s *LinkedListQueue) toList() *list.List {
|
||||
return s.data
|
||||
}
|
||||
61
codes/go/chapter_stack_and_queue/linkedlist_stack.go
Normal file
61
codes/go/chapter_stack_and_queue/linkedlist_stack.go
Normal file
@ -0,0 +1,61 @@
|
||||
// File: linkedlist_stack.go
|
||||
// Created Time: 2022-11-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
)
|
||||
|
||||
/* 基于链表实现的栈 */
|
||||
type LinkedListStack struct {
|
||||
// 使用内置包 list 来实现栈
|
||||
data *list.List
|
||||
}
|
||||
|
||||
// NewLinkedListStack 初始化链表
|
||||
func NewLinkedListStack() *LinkedListStack {
|
||||
return &LinkedListStack{
|
||||
data: list.New(),
|
||||
}
|
||||
}
|
||||
|
||||
// Push 入栈
|
||||
func (s *LinkedListStack) Push(value int) {
|
||||
s.data.PushBack(value)
|
||||
}
|
||||
|
||||
// Pop 出栈
|
||||
func (s *LinkedListStack) Pop() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Back()
|
||||
s.data.Remove(e)
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// Peek 访问栈顶元素
|
||||
func (s *LinkedListStack) Peek() any {
|
||||
if s.IsEmpty() {
|
||||
return nil
|
||||
}
|
||||
e := s.data.Back()
|
||||
return e.Value
|
||||
}
|
||||
|
||||
// Size 获取栈的长度
|
||||
func (s *LinkedListStack) Size() int {
|
||||
return s.data.Len()
|
||||
}
|
||||
|
||||
// IsEmpty 判断栈是否为空
|
||||
func (s *LinkedListStack) IsEmpty() bool {
|
||||
return s.data.Len() == 0
|
||||
}
|
||||
|
||||
// 获取 List 用于打印
|
||||
func (s *LinkedListStack) toList() *list.List {
|
||||
return s.data
|
||||
}
|
||||
134
codes/go/chapter_stack_and_queue/queue_test.go
Normal file
134
codes/go/chapter_stack_and_queue/queue_test.go
Normal file
@ -0,0 +1,134 @@
|
||||
// File: queue_test.go
|
||||
// Created Time: 2022-11-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestQueue(t *testing.T) {
|
||||
/* 初始化队列 */
|
||||
// 在 Go 中,将 list 作为队列来使用
|
||||
queue := list.New()
|
||||
|
||||
/* 元素入队 */
|
||||
queue.PushBack(1)
|
||||
queue.PushBack(3)
|
||||
queue.PushBack(2)
|
||||
queue.PushBack(5)
|
||||
queue.PushBack(4)
|
||||
fmt.Print("队列 queue = ")
|
||||
PrintList(queue)
|
||||
|
||||
/* 访问队首元素 */
|
||||
peek := queue.Front()
|
||||
fmt.Println("队首元素 peek =", peek.Value)
|
||||
|
||||
/* 元素出队 */
|
||||
poll := queue.Front()
|
||||
queue.Remove(poll)
|
||||
fmt.Print("出队元素 poll = ", poll.Value, ",出队后 queue = ")
|
||||
PrintList(queue)
|
||||
|
||||
/* 获取队列的长度 */
|
||||
size := queue.Len()
|
||||
fmt.Println("队列长度 size =", size)
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
isEmpty := queue.Len() == 0
|
||||
fmt.Println("队列是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
func TestArrayQueue(t *testing.T) {
|
||||
// 初始化队列,使用队列的通用接口
|
||||
capacity := 10
|
||||
queue := NewArrayQueue(capacity)
|
||||
|
||||
// 元素入队
|
||||
queue.Offer(1)
|
||||
queue.Offer(3)
|
||||
queue.Offer(2)
|
||||
queue.Offer(5)
|
||||
queue.Offer(4)
|
||||
fmt.Print("队列 queue = ")
|
||||
PrintSlice(queue.toSlice())
|
||||
|
||||
// 访问队首元素
|
||||
peek := queue.Peek()
|
||||
fmt.Println("队首元素 peek =", peek)
|
||||
|
||||
// 元素出队
|
||||
poll := queue.Poll()
|
||||
fmt.Print("出队元素 poll = ", poll, ", 出队后 queue = ")
|
||||
PrintSlice(queue.toSlice())
|
||||
|
||||
// 获取队的长度
|
||||
size := queue.Size()
|
||||
fmt.Println("队的长度 size =", size)
|
||||
|
||||
// 判断是否为空
|
||||
isEmpty := queue.IsEmpty()
|
||||
fmt.Println("队是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
func TestLinkedListQueue(t *testing.T) {
|
||||
// 初始化队
|
||||
queue := NewLinkedListQueue()
|
||||
|
||||
// 元素入队
|
||||
queue.Offer(1)
|
||||
queue.Offer(3)
|
||||
queue.Offer(2)
|
||||
queue.Offer(5)
|
||||
queue.Offer(4)
|
||||
fmt.Print("队列 queue = ")
|
||||
PrintList(queue.toList())
|
||||
|
||||
// 访问队首元素
|
||||
peek := queue.Peek()
|
||||
fmt.Println("队首元素 peek =", peek)
|
||||
|
||||
// 元素出队
|
||||
poll := queue.Poll()
|
||||
fmt.Print("出队元素 poll = ", poll, ", 出队后 queue = ")
|
||||
PrintList(queue.toList())
|
||||
|
||||
// 获取队的长度
|
||||
size := queue.Size()
|
||||
fmt.Println("队的长度 size =", size)
|
||||
|
||||
// 判断是否为空
|
||||
isEmpty := queue.IsEmpty()
|
||||
fmt.Println("队是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
// BenchmarkArrayQueue 8 ns/op in Mac M1 Pro
|
||||
func BenchmarkArrayQueue(b *testing.B) {
|
||||
capacity := 1000
|
||||
stack := NewArrayQueue(capacity)
|
||||
// use b.N for looping
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Offer(777)
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Poll()
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkLinkedQueue 62.66 ns/op in Mac M1 Pro
|
||||
func BenchmarkLinkedQueue(b *testing.B) {
|
||||
stack := NewLinkedListQueue()
|
||||
// use b.N for looping
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Offer(777)
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Poll()
|
||||
}
|
||||
}
|
||||
130
codes/go/chapter_stack_and_queue/stack_test.go
Normal file
130
codes/go/chapter_stack_and_queue/stack_test.go
Normal file
@ -0,0 +1,130 @@
|
||||
// File: stack_test.go
|
||||
// Created Time: 2022-11-28
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_stack_and_queue
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestStack(t *testing.T) {
|
||||
/* 初始化栈 */
|
||||
// 在 Go 中,推荐将 Slice 当作栈来使用
|
||||
var stack []int
|
||||
|
||||
/* 元素入栈 */
|
||||
stack = append(stack, 1)
|
||||
stack = append(stack, 3)
|
||||
stack = append(stack, 2)
|
||||
stack = append(stack, 5)
|
||||
stack = append(stack, 4)
|
||||
fmt.Print("栈 = ")
|
||||
PrintSlice(stack)
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
peek := stack[len(stack)-1]
|
||||
fmt.Println("栈顶元素 peek =", peek)
|
||||
|
||||
/* 元素出栈 */
|
||||
pop := stack[len(stack)-1]
|
||||
stack = stack[:len(stack)-1]
|
||||
fmt.Print("出栈元素 pop = ", pop, ",出栈后 stack = ")
|
||||
PrintSlice(stack)
|
||||
|
||||
/* 获取栈的长度 */
|
||||
size := len(stack)
|
||||
fmt.Println("栈的长度 size =", size)
|
||||
|
||||
/* 判断是否为空 */
|
||||
isEmpty := len(stack) == 0
|
||||
fmt.Println("栈是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
func TestArrayStack(t *testing.T) {
|
||||
// 初始化栈, 使用接口承接
|
||||
stack := NewArrayStack()
|
||||
|
||||
// 元素入栈
|
||||
stack.Push(1)
|
||||
stack.Push(3)
|
||||
stack.Push(2)
|
||||
stack.Push(5)
|
||||
stack.Push(4)
|
||||
fmt.Print("栈 stack = ")
|
||||
PrintSlice(stack.toSlice())
|
||||
|
||||
// 访问栈顶元素
|
||||
peek := stack.Peek()
|
||||
fmt.Println("栈顶元素 peek =", peek)
|
||||
|
||||
// 元素出栈
|
||||
pop := stack.Pop()
|
||||
fmt.Print("出栈元素 pop = ", pop, ", 出栈后 stack = ")
|
||||
PrintSlice(stack.toSlice())
|
||||
|
||||
// 获取栈的长度
|
||||
size := stack.Size()
|
||||
fmt.Println("栈的长度 size =", size)
|
||||
|
||||
// 判断是否为空
|
||||
isEmpty := stack.IsEmpty()
|
||||
fmt.Println("栈是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
func TestLinkedListStack(t *testing.T) {
|
||||
// 初始化栈
|
||||
stack := NewLinkedListStack()
|
||||
// 元素入栈
|
||||
stack.Push(1)
|
||||
stack.Push(3)
|
||||
stack.Push(2)
|
||||
stack.Push(5)
|
||||
stack.Push(4)
|
||||
fmt.Print("栈 stack = ")
|
||||
PrintList(stack.toList())
|
||||
|
||||
// 访问栈顶元素
|
||||
peek := stack.Peek()
|
||||
fmt.Println("栈顶元素 peek =", peek)
|
||||
|
||||
// 元素出栈
|
||||
pop := stack.Pop()
|
||||
fmt.Print("出栈元素 pop = ", pop, ", 出栈后 stack = ")
|
||||
PrintList(stack.toList())
|
||||
|
||||
// 获取栈的长度
|
||||
size := stack.Size()
|
||||
fmt.Println("栈的长度 size =", size)
|
||||
|
||||
// 判断是否为空
|
||||
isEmpty := stack.IsEmpty()
|
||||
fmt.Println("栈是否为空 =", isEmpty)
|
||||
}
|
||||
|
||||
// BenchmarkArrayStack 8 ns/op in Mac M1 Pro
|
||||
func BenchmarkArrayStack(b *testing.B) {
|
||||
stack := NewArrayStack()
|
||||
// use b.N for looping
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Push(777)
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Pop()
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkLinkedListStack 65.02 ns/op in Mac M1 Pro
|
||||
func BenchmarkLinkedListStack(b *testing.B) {
|
||||
stack := NewLinkedListStack()
|
||||
// use b.N for looping
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Push(777)
|
||||
}
|
||||
for i := 0; i < b.N; i++ {
|
||||
stack.Pop()
|
||||
}
|
||||
}
|
||||
@ -5,8 +5,9 @@
|
||||
package chapter_tree
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
"sort"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
type BinarySearchTree struct {
|
||||
@ -52,7 +53,7 @@ func (bst *BinarySearchTree) GetInorderNext(node *TreeNode) *TreeNode {
|
||||
return node
|
||||
}
|
||||
|
||||
// Search node of binary search tree
|
||||
/* 查找结点 */
|
||||
func (bst *BinarySearchTree) Search(num int) *TreeNode {
|
||||
node := bst.root
|
||||
// 循环查找,越过叶结点后跳出
|
||||
@ -72,7 +73,7 @@ func (bst *BinarySearchTree) Search(num int) *TreeNode {
|
||||
return node
|
||||
}
|
||||
|
||||
// Insert node of binary search tree
|
||||
/* 插入结点 */
|
||||
func (bst *BinarySearchTree) Insert(num int) *TreeNode {
|
||||
cur := bst.root
|
||||
// 若树为空,直接提前返回
|
||||
@ -103,7 +104,7 @@ func (bst *BinarySearchTree) Insert(num int) *TreeNode {
|
||||
return cur
|
||||
}
|
||||
|
||||
// Remove node of binary search tree
|
||||
/* 删除结点 */
|
||||
func (bst *BinarySearchTree) Remove(num int) *TreeNode {
|
||||
cur := bst.root
|
||||
// 若树为空,直接提前返回
|
||||
@ -118,8 +119,8 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode {
|
||||
break
|
||||
}
|
||||
prev = cur
|
||||
// 待删除结点在右子树中
|
||||
if cur.Val < num {
|
||||
// 待删除结点在右子树中
|
||||
cur = cur.Right
|
||||
} else {
|
||||
// 待删除结点在左子树中
|
||||
@ -145,8 +146,8 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode {
|
||||
} else {
|
||||
prev.Right = child
|
||||
}
|
||||
|
||||
} else { // 子结点数为 2
|
||||
// 子结点数为 2
|
||||
} else {
|
||||
// 获取中序遍历中待删除结点 cur 的下一个结点
|
||||
next := bst.GetInorderNext(cur)
|
||||
temp := next.Val
|
||||
@ -155,7 +156,6 @@ func (bst *BinarySearchTree) Remove(num int) *TreeNode {
|
||||
// 将 next 的值复制给 cur
|
||||
cur.Val = temp
|
||||
}
|
||||
// TODO: add error handler, don't return node
|
||||
return cur
|
||||
}
|
||||
|
||||
|
||||
@ -4,38 +4,41 @@
|
||||
|
||||
package chapter_tree
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBinarySearchTree(t *testing.T) {
|
||||
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
||||
bst := NewBinarySearchTree(nums)
|
||||
t.Log("初始化的二叉树为:")
|
||||
fmt.Println("初始化的二叉树为:")
|
||||
bst.Print()
|
||||
|
||||
// 获取根结点
|
||||
node := bst.GetRoot()
|
||||
t.Log("二叉树的根结点为:", node.Val)
|
||||
fmt.Println("二叉树的根结点为:", node.Val)
|
||||
// 获取最小的结点
|
||||
node = bst.GetMin(bst.GetRoot())
|
||||
t.Log("二叉树的最小结点为:", node.Val)
|
||||
fmt.Println("二叉树的最小结点为:", node.Val)
|
||||
|
||||
// 查找结点
|
||||
node = bst.Search(5)
|
||||
t.Log("查找到的结点对象为", node, ",结点值 =", node.Val)
|
||||
fmt.Println("查找到的结点对象为", node, ",结点值 =", node.Val)
|
||||
|
||||
// 插入结点
|
||||
node = bst.Insert(16)
|
||||
t.Log("插入结点后 16 的二叉树为:")
|
||||
fmt.Println("插入结点后 16 的二叉树为:")
|
||||
bst.Print()
|
||||
|
||||
// 删除结点
|
||||
bst.Remove(1)
|
||||
t.Log("删除结点 1 后的二叉树为:")
|
||||
fmt.Println("删除结点 1 后的二叉树为:")
|
||||
bst.Print()
|
||||
bst.Remove(2)
|
||||
t.Log("删除结点 2 后的二叉树为:")
|
||||
fmt.Println("删除结点 2 后的二叉树为:")
|
||||
bst.Print()
|
||||
bst.Remove(4)
|
||||
t.Log("删除结点 4 后的二叉树为:")
|
||||
fmt.Println("删除结点 4 后的二叉树为:")
|
||||
bst.Print()
|
||||
}
|
||||
|
||||
@ -1,23 +0,0 @@
|
||||
// File: binary_tree.go
|
||||
// Created Time: 2022-11-25
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_tree
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
type BinaryTree struct {
|
||||
root *TreeNode
|
||||
}
|
||||
|
||||
func NewBinaryTree(node *TreeNode) *BinaryTree {
|
||||
return &BinaryTree{
|
||||
root: node,
|
||||
}
|
||||
}
|
||||
|
||||
func (tree *BinaryTree) Print() {
|
||||
PrintTree(tree.root)
|
||||
}
|
||||
@ -6,14 +6,14 @@ package chapter_tree
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
// levelOrder Breadth First Search
|
||||
/* 层序遍历 */
|
||||
func levelOrder(root *TreeNode) []int {
|
||||
// Let container.list as queue
|
||||
queue := list.New()
|
||||
// 初始化队列,加入根结点
|
||||
queue := list.New()
|
||||
queue.PushBack(root)
|
||||
// 初始化一个切片,用于保存遍历序列
|
||||
nums := make([]int, 0)
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
package chapter_tree
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
@ -14,10 +15,10 @@ func TestLevelOrder(t *testing.T) {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
root := ArrayToTree([]int{1, 2, 3, 4, 5, 6, 7})
|
||||
t.Log("初始化二叉树: ")
|
||||
fmt.Println("初始化二叉树: ")
|
||||
PrintTree(root)
|
||||
|
||||
// 层序遍历
|
||||
nums := levelOrder(root)
|
||||
t.Log("层序遍历的结点打印序列 =", nums)
|
||||
fmt.Println("层序遍历的结点打印序列 =", nums)
|
||||
}
|
||||
|
||||
@ -8,56 +8,37 @@ import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
// preOrder 前序遍历
|
||||
func preOrder(root *TreeNode) (nums []int) {
|
||||
var preOrderHelper func(node *TreeNode)
|
||||
// 匿名函数
|
||||
preOrderHelper = func(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// 访问优先级:根结点 -> 左子树 -> 右子树
|
||||
nums = append(nums, node.Val)
|
||||
preOrderHelper(node.Left)
|
||||
preOrderHelper(node.Right)
|
||||
var nums []int
|
||||
|
||||
/* 前序遍历 */
|
||||
func preOrder(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// 函数调用
|
||||
preOrderHelper(root)
|
||||
return
|
||||
// 访问优先级:根结点 -> 左子树 -> 右子树
|
||||
nums = append(nums, node.Val)
|
||||
preOrder(node.Left)
|
||||
preOrder(node.Right)
|
||||
}
|
||||
|
||||
// inOrder 中序遍历
|
||||
func inOrder(root *TreeNode) (nums []int) {
|
||||
var inOrderHelper func(node *TreeNode)
|
||||
// 匿名函数
|
||||
inOrderHelper = func(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// 访问优先级:左子树 -> 根结点 -> 右子树
|
||||
inOrderHelper(node.Left)
|
||||
nums = append(nums, node.Val)
|
||||
inOrderHelper(node.Right)
|
||||
/* 中序遍历 */
|
||||
func inOrder(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// 函数调用
|
||||
inOrderHelper(root)
|
||||
return
|
||||
// 访问优先级:左子树 -> 根结点 -> 右子树
|
||||
inOrder(node.Left)
|
||||
nums = append(nums, node.Val)
|
||||
inOrder(node.Right)
|
||||
}
|
||||
|
||||
// postOrder 后序遍历
|
||||
func postOrder(root *TreeNode) (nums []int) {
|
||||
var postOrderHelper func(node *TreeNode)
|
||||
// 匿名函数
|
||||
postOrderHelper = func(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// 访问优先级:左子树 -> 右子树 -> 根结点
|
||||
postOrderHelper(node.Left)
|
||||
postOrderHelper(node.Right)
|
||||
nums = append(nums, node.Val)
|
||||
/* 后序遍历 */
|
||||
func postOrder(node *TreeNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
// 函数调用
|
||||
postOrderHelper(root)
|
||||
return
|
||||
// 访问优先级:左子树 -> 右子树 -> 根结点
|
||||
postOrder(node.Left)
|
||||
postOrder(node.Right)
|
||||
nums = append(nums, node.Val)
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
package chapter_tree
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
@ -14,18 +15,21 @@ func TestPreInPostOrderTraversal(t *testing.T) {
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
root := ArrayToTree([]int{1, 2, 3, 4, 5, 6, 7})
|
||||
t.Log("初始化二叉树: ")
|
||||
fmt.Println("初始化二叉树: ")
|
||||
PrintTree(root)
|
||||
|
||||
// 前序遍历
|
||||
nums := preOrder(root)
|
||||
t.Log("前序遍历的结点打印序列 =", nums)
|
||||
nums = nil
|
||||
preOrder(root)
|
||||
fmt.Println("前序遍历的结点打印序列 =", nums)
|
||||
|
||||
// 中序遍历
|
||||
nums = inOrder(root)
|
||||
t.Log("中序遍历的结点打印序列 =", nums)
|
||||
nums = nil
|
||||
inOrder(root)
|
||||
fmt.Println("中序遍历的结点打印序列 =", nums)
|
||||
|
||||
// 后序遍历
|
||||
nums = postOrder(root)
|
||||
t.Log("后序遍历的结点打印序列 =", nums)
|
||||
nums = nil
|
||||
postOrder(root)
|
||||
fmt.Println("后序遍历的结点打印序列 =", nums)
|
||||
}
|
||||
|
||||
@ -5,8 +5,10 @@
|
||||
package chapter_tree
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestBinaryTree(t *testing.T) {
|
||||
@ -17,24 +19,23 @@ func TestBinaryTree(t *testing.T) {
|
||||
n3 := NewTreeNode(3)
|
||||
n4 := NewTreeNode(4)
|
||||
n5 := NewTreeNode(5)
|
||||
|
||||
tree := NewBinaryTree(n1)
|
||||
// 构建引用指向(即指针)
|
||||
n1.Left = n2
|
||||
n1.Right = n3
|
||||
n2.Left = n4
|
||||
n2.Right = n5
|
||||
t.Log("初始化二叉树")
|
||||
tree.Print()
|
||||
fmt.Println("初始化二叉树")
|
||||
PrintTree(n1)
|
||||
|
||||
/* 插入与删除结点 */
|
||||
// 插入结点
|
||||
p := NewTreeNode(0)
|
||||
n1.Left = p
|
||||
p.Left = n2
|
||||
t.Log("插入结点 P 后")
|
||||
tree.Print()
|
||||
|
||||
fmt.Println("插入结点 P 后")
|
||||
PrintTree(n1)
|
||||
// 删除结点
|
||||
n1.Left = n2
|
||||
t.Log("删除结点 P 后")
|
||||
tree.Print()
|
||||
fmt.Println("删除结点 P 后")
|
||||
PrintTree(n1)
|
||||
}
|
||||
|
||||
@ -4,12 +4,6 @@
|
||||
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ListNode Definition for a singly-linked list node
|
||||
type ListNode struct {
|
||||
Next *ListNode
|
||||
@ -43,17 +37,3 @@ func GetListNode(node *ListNode, val int) *ListNode {
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// PrintLinkedList Print a linked list
|
||||
func PrintLinkedList(node *ListNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
var builder strings.Builder
|
||||
for node.Next != nil {
|
||||
builder.WriteString(strconv.Itoa(node.Val) + " -> ")
|
||||
node = node.Next
|
||||
}
|
||||
builder.WriteString(strconv.Itoa(node.Val))
|
||||
fmt.Println(builder.String())
|
||||
}
|
||||
|
||||
@ -4,7 +4,10 @@
|
||||
|
||||
package pkg
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestListNode(t *testing.T) {
|
||||
arr := []int{2, 3, 5, 6, 7}
|
||||
@ -12,5 +15,5 @@ func TestListNode(t *testing.T) {
|
||||
|
||||
PrintLinkedList(head)
|
||||
node := GetListNode(head, 5)
|
||||
t.Log("Find node: ", node.Val)
|
||||
fmt.Println("Find node: ", node.Val)
|
||||
}
|
||||
|
||||
98
codes/go/pkg/print_utils.go
Normal file
98
codes/go/pkg/print_utils.go
Normal file
@ -0,0 +1,98 @@
|
||||
// File: print_utils.go
|
||||
// Created Time: 2022-12-03
|
||||
// Author: Reanon (793584285@qq.com), Krahets (krahets@163.com)
|
||||
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func PrintSlice(nums []int) {
|
||||
fmt.Printf("%v", nums)
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// PrintList Print a list
|
||||
func PrintList(list *list.List) {
|
||||
e := list.Front()
|
||||
// 强转为 string, 会影响效率
|
||||
fmt.Print("[")
|
||||
for e.Next() != nil {
|
||||
fmt.Print(e.Value, " ")
|
||||
e = e.Next()
|
||||
}
|
||||
fmt.Print(e.Value, "]\n")
|
||||
}
|
||||
|
||||
// PrintLinkedList Print a linked list
|
||||
func PrintLinkedList(node *ListNode) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
var builder strings.Builder
|
||||
for node.Next != nil {
|
||||
builder.WriteString(strconv.Itoa(node.Val) + " -> ")
|
||||
node = node.Next
|
||||
}
|
||||
builder.WriteString(strconv.Itoa(node.Val))
|
||||
fmt.Println(builder.String())
|
||||
}
|
||||
|
||||
// PrintTree Print a binary tree
|
||||
func PrintTree(root *TreeNode) {
|
||||
printTreeHelper(root, nil, false)
|
||||
}
|
||||
|
||||
// printTreeHelper Help to print a binary tree, hide more details
|
||||
// This tree printer is borrowed from TECHIE DELIGHT
|
||||
// https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
prevStr := " "
|
||||
trunk := newTrunk(prev, prevStr)
|
||||
printTreeHelper(root.Right, trunk, true)
|
||||
if prev == nil {
|
||||
trunk.str = "———"
|
||||
} else if isLeft {
|
||||
trunk.str = "/———"
|
||||
prevStr = " |"
|
||||
} else {
|
||||
trunk.str = "\\———"
|
||||
prev.str = prevStr
|
||||
}
|
||||
showTrunk(trunk)
|
||||
fmt.Println(root.Val)
|
||||
if prev != nil {
|
||||
prev.str = prevStr
|
||||
}
|
||||
trunk.str = " |"
|
||||
printTreeHelper(root.Left, trunk, false)
|
||||
}
|
||||
|
||||
// trunk Help to Print tree structure
|
||||
type trunk struct {
|
||||
prev *trunk
|
||||
str string
|
||||
}
|
||||
|
||||
func newTrunk(prev *trunk, str string) *trunk {
|
||||
return &trunk{
|
||||
prev: prev,
|
||||
str: str,
|
||||
}
|
||||
}
|
||||
|
||||
func showTrunk(t *trunk) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
|
||||
showTrunk(t.prev)
|
||||
fmt.Print(t.str)
|
||||
}
|
||||
@ -6,7 +6,6 @@ package pkg
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type TreeNode struct {
|
||||
@ -71,58 +70,3 @@ func TreeToArray(root *TreeNode) []any {
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
// PrintTree Print a binary tree
|
||||
func PrintTree(root *TreeNode) {
|
||||
printTreeHelper(root, nil, false)
|
||||
}
|
||||
|
||||
// printTreeHelper Help to print a binary tree, hide more details
|
||||
// This tree printer is borrowed from TECHIE DELIGHT
|
||||
// https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
prevStr := " "
|
||||
trunk := newTrunk(prev, prevStr)
|
||||
printTreeHelper(root.Right, trunk, true)
|
||||
if prev == nil {
|
||||
trunk.str = "———"
|
||||
} else if isLeft {
|
||||
trunk.str = "/———"
|
||||
prevStr = " |"
|
||||
} else {
|
||||
trunk.str = "\\———"
|
||||
prev.str = prevStr
|
||||
}
|
||||
showTrunk(trunk)
|
||||
fmt.Println(root.Val)
|
||||
if prev != nil {
|
||||
prev.str = prevStr
|
||||
}
|
||||
trunk.str = " |"
|
||||
printTreeHelper(root.Left, trunk, false)
|
||||
}
|
||||
|
||||
// trunk Help to Print tree structure
|
||||
type trunk struct {
|
||||
prev *trunk
|
||||
str string
|
||||
}
|
||||
|
||||
func newTrunk(prev *trunk, str string) *trunk {
|
||||
return &trunk{
|
||||
prev: prev,
|
||||
str: str,
|
||||
}
|
||||
}
|
||||
|
||||
func showTrunk(t *trunk) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
|
||||
showTrunk(t.prev)
|
||||
fmt.Print(t.str)
|
||||
}
|
||||
|
||||
@ -4,7 +4,10 @@
|
||||
|
||||
package pkg
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTreeNode(t *testing.T) {
|
||||
arr := []int{2, 3, 5, 6, 7}
|
||||
@ -14,5 +17,5 @@ func TestTreeNode(t *testing.T) {
|
||||
PrintTree(node)
|
||||
|
||||
// tree to arr
|
||||
t.Log(TreeToArray(node))
|
||||
fmt.Println(TreeToArray(node))
|
||||
}
|
||||
|
||||
@ -56,13 +56,13 @@ class MyList {
|
||||
}
|
||||
|
||||
/* 中间插入元素 */
|
||||
public void add(int index, int num) {
|
||||
public void insert(int index, int num) {
|
||||
if (index >= size)
|
||||
throw new IndexOutOfBoundsException("索引越界");
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (size == capacity())
|
||||
extendCapacity();
|
||||
// 索引 i 以及之后的元素都向后移动一位
|
||||
// 将索引 index 以及之后的元素都向后移动一位
|
||||
for (int j = size - 1; j >= index; j--) {
|
||||
nums[j + 1] = nums[j];
|
||||
}
|
||||
@ -72,15 +72,18 @@ class MyList {
|
||||
}
|
||||
|
||||
/* 删除元素 */
|
||||
public void remove(int index) {
|
||||
public int remove(int index) {
|
||||
if (index >= size)
|
||||
throw new IndexOutOfBoundsException("索引越界");
|
||||
// 索引 i 之后的元素都向前移动一位
|
||||
int num = nums[index];
|
||||
// 将索引 index 之后的元素都向前移动一位
|
||||
for (int j = index; j < size - 1; j++) {
|
||||
nums[j] = nums[j + 1];
|
||||
}
|
||||
// 更新元素数量
|
||||
size--;
|
||||
// 返回被删除元素
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 列表扩容 */
|
||||
@ -118,7 +121,7 @@ public class my_list {
|
||||
" ,容量 = " + list.capacity() + " ,长度 = " + list.size());
|
||||
|
||||
/* 中间插入元素 */
|
||||
list.add(3, 6);
|
||||
list.insert(3, 6);
|
||||
System.out.println("在索引 3 处插入数字 6 ,得到 list = " + Arrays.toString(list.toArray()));
|
||||
|
||||
/* 删除元素 */
|
||||
|
||||
138
codes/java/chapter_hashing/array_hash_map.java
Normal file
138
codes/java/chapter_hashing/array_hash_map.java
Normal file
@ -0,0 +1,138 @@
|
||||
/*
|
||||
* File: hash_map.java
|
||||
* Created Time: 2022-12-04
|
||||
* Author: Krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_hashing;
|
||||
import java.util.*;
|
||||
|
||||
/* 键值对 int->String */
|
||||
class Entry {
|
||||
public int key;
|
||||
public String val;
|
||||
public Entry(int key, String val) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* 基于数组简易实现的哈希表 */
|
||||
class ArrayHashMap {
|
||||
private List<Entry> bucket;
|
||||
public ArrayHashMap() {
|
||||
// 初始化一个长度为 10 的桶(数组)
|
||||
bucket = new ArrayList<>(10);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
bucket.add(null);
|
||||
}
|
||||
}
|
||||
|
||||
/* 哈希函数 */
|
||||
private int hashFunc(int key) {
|
||||
int index = key % 10000;
|
||||
return index;
|
||||
}
|
||||
|
||||
/* 查询操作 */
|
||||
public String get(int key) {
|
||||
int index = hashFunc(key);
|
||||
Entry pair = bucket.get(index);
|
||||
if (pair == null) return null;
|
||||
return pair.val;
|
||||
}
|
||||
|
||||
/* 添加操作 */
|
||||
public void put(int key, String val) {
|
||||
Entry pair = new Entry(key, val);
|
||||
int index = hashFunc(key);
|
||||
bucket.set(index, pair);
|
||||
}
|
||||
|
||||
/* 删除操作 */
|
||||
public void remove(int key) {
|
||||
int index = hashFunc(key);
|
||||
// 置为空字符,代表删除
|
||||
bucket.set(index, null);
|
||||
}
|
||||
|
||||
/* 获取所有键值对 */
|
||||
public List<Entry> entrySet() {
|
||||
List<Entry> entrySet = new ArrayList<>();
|
||||
for (Entry pair : bucket) {
|
||||
if (pair != null)
|
||||
entrySet.add(pair);
|
||||
}
|
||||
return entrySet;
|
||||
}
|
||||
|
||||
/* 获取所有键 */
|
||||
public List<Integer> keySet() {
|
||||
List<Integer> keySet = new ArrayList<>();
|
||||
for (Entry pair : bucket) {
|
||||
if (pair != null)
|
||||
keySet.add(pair.key);
|
||||
}
|
||||
return keySet;
|
||||
}
|
||||
|
||||
/* 获取所有值 */
|
||||
public List<String> valueSet() {
|
||||
List<String> valueSet = new ArrayList<>();
|
||||
for (Entry pair : bucket) {
|
||||
if (pair != null)
|
||||
valueSet.add(pair.val);
|
||||
}
|
||||
return valueSet;
|
||||
}
|
||||
|
||||
/* 打印哈希表 */
|
||||
public void print() {
|
||||
for (Entry kv: entrySet()) {
|
||||
System.out.println(kv.key + " -> " + kv.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class array_hash_map {
|
||||
public static void main(String[] args) {
|
||||
/* 初始化哈希表 */
|
||||
ArrayHashMap map = new ArrayHashMap();
|
||||
|
||||
/* 添加操作 */
|
||||
// 在哈希表中添加键值对 (key, value)
|
||||
map.put(10001, "小哈");
|
||||
map.put(10002, "小啰");
|
||||
map.put(10003, "小算");
|
||||
map.put(10004, "小法");
|
||||
map.put(10005, "小哇");
|
||||
System.out.println("\n添加完成后,哈希表为\nKey -> Value");
|
||||
map.print();
|
||||
|
||||
/* 查询操作 */
|
||||
// 向哈希表输入键 key ,得到值 value
|
||||
String name = map.get(10002);
|
||||
System.out.println("\n输入学号 10002 ,查询到姓名 " + name);
|
||||
|
||||
/* 删除操作 */
|
||||
// 在哈希表中删除键值对 (key, value)
|
||||
map.remove(10005);
|
||||
System.out.println("\n删除 10005 后,哈希表为\nKey -> Value");
|
||||
map.print();
|
||||
|
||||
/* 遍历哈希表 */
|
||||
System.out.println("\n遍历键值对 Key->Value");
|
||||
for (Entry kv: map.entrySet()) {
|
||||
System.out.println(kv.key + " -> " + kv.val);
|
||||
}
|
||||
System.out.println("\n单独遍历键 Key");
|
||||
for (int key: map.keySet()) {
|
||||
System.out.println(key);
|
||||
}
|
||||
System.out.println("\n单独遍历值 Value");
|
||||
for (String val: map.valueSet()) {
|
||||
System.out.println(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
51
codes/java/chapter_hashing/hash_map.java
Normal file
51
codes/java/chapter_hashing/hash_map.java
Normal file
@ -0,0 +1,51 @@
|
||||
/*
|
||||
* File: hash_map.java
|
||||
* Created Time: 2022-12-04
|
||||
* Author: Krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
package chapter_hashing;
|
||||
import java.util.*;
|
||||
import include.*;
|
||||
|
||||
public class hash_map {
|
||||
public static void main(String[] args) {
|
||||
/* 初始化哈希表 */
|
||||
Map<Integer, String> map = new HashMap<>();
|
||||
|
||||
/* 添加操作 */
|
||||
// 在哈希表中添加键值对 (key, value)
|
||||
map.put(10001, "小哈");
|
||||
map.put(10002, "小啰");
|
||||
map.put(10003, "小算");
|
||||
map.put(10004, "小法");
|
||||
map.put(10005, "小哇");
|
||||
System.out.println("\n添加完成后,哈希表为\nKey -> Value");
|
||||
PrintUtil.printHashMap(map);
|
||||
|
||||
/* 查询操作 */
|
||||
// 向哈希表输入键 key ,得到值 value
|
||||
String name = map.get(10002);
|
||||
System.out.println("\n输入学号 10002 ,查询到姓名 " + name);
|
||||
|
||||
/* 删除操作 */
|
||||
// 在哈希表中删除键值对 (key, value)
|
||||
map.remove(10005);
|
||||
System.out.println("\n删除 10005 后,哈希表为\nKey -> Value");
|
||||
PrintUtil.printHashMap(map);
|
||||
|
||||
/* 遍历哈希表 */
|
||||
System.out.println("\n遍历键值对 Key->Value");
|
||||
for (Map.Entry <Integer, String> kv: map.entrySet()) {
|
||||
System.out.println(kv.getKey() + " -> " + kv.getValue());
|
||||
}
|
||||
System.out.println("\n单独遍历键 Key");
|
||||
for (int key: map.keySet()) {
|
||||
System.out.println(key);
|
||||
}
|
||||
System.out.println("\n单独遍历值 Value");
|
||||
for (String val: map.values()) {
|
||||
System.out.println(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -10,10 +10,9 @@ import java.util.*;
|
||||
|
||||
/* 基于环形数组实现的队列 */
|
||||
class ArrayQueue {
|
||||
int[] nums; // 用于存储队列元素的数组
|
||||
int size = 0; // 队列长度(即元素个数)
|
||||
int front = 0; // 头指针,指向队首
|
||||
int rear = 0; // 尾指针,指向队尾 + 1
|
||||
private int[] nums; // 用于存储队列元素的数组
|
||||
private int front = 0; // 头指针,指向队首
|
||||
private int rear = 0; // 尾指针,指向队尾 + 1
|
||||
|
||||
public ArrayQueue(int capacity) {
|
||||
// 初始化数组
|
||||
@ -51,11 +50,8 @@ class ArrayQueue {
|
||||
|
||||
/* 出队 */
|
||||
public int poll() {
|
||||
// 删除头结点
|
||||
if (isEmpty())
|
||||
throw new EmptyStackException();
|
||||
int num = nums[front];
|
||||
// 队头指针向后移动,越过尾部后返回到数组头部
|
||||
int num = peek();
|
||||
// 队头指针向后移动一位,若越过尾部则返回到数组头部
|
||||
front = (front + 1) % capacity();
|
||||
return num;
|
||||
}
|
||||
@ -68,15 +64,23 @@ class ArrayQueue {
|
||||
return nums[front];
|
||||
}
|
||||
|
||||
/* 访问索引 index 处元素 */
|
||||
int get(int index) {
|
||||
if (index >= size())
|
||||
throw new IndexOutOfBoundsException();
|
||||
return nums[(front + index) % capacity()];
|
||||
}
|
||||
|
||||
/* 返回数组 */
|
||||
public int[] toArray() {
|
||||
int size = size();
|
||||
int capacity = capacity();
|
||||
// 仅转换有效长度范围内的列表元素
|
||||
int[] arr = new int[size];
|
||||
int[] res = new int[size];
|
||||
for (int i = 0, j = front; i < size; i++, j++) {
|
||||
arr[i] = nums[j % capacity];
|
||||
res[i] = nums[j % capacity];
|
||||
}
|
||||
return arr;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
@ -108,12 +112,13 @@ public class array_queue {
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
boolean isEmpty = queue.isEmpty();
|
||||
System.out.println("队列是否为空 = " + isEmpty);
|
||||
|
||||
/* 测试环形数组 */
|
||||
for (int i = 0; i < 10; i++) {
|
||||
queue.offer(i);
|
||||
queue.poll();
|
||||
System.out.println("第 " + i + " 轮入队+出队后 queue = " + Arrays.toString(queue.toArray()));
|
||||
System.out.println("第 " + i + " 轮入队 + 出队后 queue = " + Arrays.toString(queue.toArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,15 +10,15 @@ import java.util.*;
|
||||
|
||||
/* 基于数组实现的栈 */
|
||||
class ArrayStack {
|
||||
ArrayList<Integer> list;
|
||||
private ArrayList<Integer> stack;
|
||||
public ArrayStack() {
|
||||
// 初始化列表(动态数组)
|
||||
list = new ArrayList<>();
|
||||
stack = new ArrayList<>();
|
||||
}
|
||||
|
||||
/* 获取栈的长度 */
|
||||
public int size() {
|
||||
return list.size();
|
||||
return stack.size();
|
||||
}
|
||||
|
||||
/* 判断栈是否为空 */
|
||||
@ -28,27 +28,27 @@ class ArrayStack {
|
||||
|
||||
/* 入栈 */
|
||||
public void push(int num) {
|
||||
list.add(num);
|
||||
stack.add(num);
|
||||
}
|
||||
|
||||
/* 出栈 */
|
||||
public int pop() {
|
||||
return list.remove(size() - 1);
|
||||
return stack.remove(size() - 1);
|
||||
}
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
public int peek() {
|
||||
return list.get(size() - 1);
|
||||
return stack.get(size() - 1);
|
||||
}
|
||||
|
||||
/* 访问索引 index 处元素 */
|
||||
public int get(int index) {
|
||||
return list.get(index);
|
||||
return stack.get(index);
|
||||
}
|
||||
|
||||
/* 将 List 转化为 Array 并返回 */
|
||||
public Object[] toArray() {
|
||||
return list.toArray();
|
||||
return stack.toArray();
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,6 +69,10 @@ public class array_stack {
|
||||
int peek = stack.peek();
|
||||
System.out.println("栈顶元素 peek = " + peek);
|
||||
|
||||
/* 访问索引 index 处元素 */
|
||||
int num = stack.get(3);
|
||||
System.out.println("栈索引 3 处的元素为 num = " + num);
|
||||
|
||||
/* 元素出栈 */
|
||||
int pop = stack.pop();
|
||||
System.out.println("出栈元素 pop = " + pop + ",出栈后 stack = " + Arrays.toString(stack.toArray()));
|
||||
@ -79,5 +83,6 @@ public class array_stack {
|
||||
|
||||
/* 判断是否为空 */
|
||||
boolean isEmpty = stack.isEmpty();
|
||||
System.out.println("栈是否为空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,7 +10,7 @@ import java.util.*;
|
||||
|
||||
public class deque {
|
||||
public static void main(String[] args) {
|
||||
/* 初始化队列 */
|
||||
/* 初始化双向队列 */
|
||||
Deque<Integer> deque = new LinkedList<>();
|
||||
|
||||
/* 元素入队 */
|
||||
@ -19,9 +19,9 @@ public class deque {
|
||||
deque.offerLast(4);
|
||||
deque.offerFirst(3);
|
||||
deque.offerFirst(1);
|
||||
System.out.println("队列 deque = " + deque);
|
||||
System.out.println("双向队列 deque = " + deque);
|
||||
|
||||
/* 访问队首元素 */
|
||||
/* 访问元素 */
|
||||
int peekFirst = deque.peekFirst();
|
||||
System.out.println("队首元素 peekFirst = " + peekFirst);
|
||||
int peekLast = deque.peekLast();
|
||||
@ -33,11 +33,12 @@ public class deque {
|
||||
int pollLast = deque.pollLast();
|
||||
System.out.println("队尾出队元素 pollLast = " + pollLast + ",队尾出队后 deque = " + deque);
|
||||
|
||||
/* 获取队列的长度 */
|
||||
/* 获取双向队列的长度 */
|
||||
int size = deque.size();
|
||||
System.out.println("队列长度 size = " + size);
|
||||
System.out.println("双向队列长度 size = " + size);
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
/* 判断双向队列是否为空 */
|
||||
boolean isEmpty = deque.isEmpty();
|
||||
System.out.println("双向队列是否为空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,46 +7,69 @@
|
||||
package chapter_stack_and_queue;
|
||||
|
||||
import java.util.*;
|
||||
import include.*;
|
||||
|
||||
/* 基于链表实现的队列 */
|
||||
class LinkedListQueue {
|
||||
LinkedList<Integer> list;
|
||||
private ListNode front, rear; // 头结点 front ,尾结点 rear
|
||||
private int queSize = 0;
|
||||
|
||||
public LinkedListQueue() {
|
||||
// 初始化链表
|
||||
list = new LinkedList<>();
|
||||
front = null;
|
||||
rear = null;
|
||||
}
|
||||
|
||||
/* 获取队列的长度 */
|
||||
public int size() {
|
||||
return list.size();
|
||||
return queSize;
|
||||
}
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
public boolean isEmpty() {
|
||||
return list.size() == 0;
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/* 入队 */
|
||||
public void offer(int num) {
|
||||
// 尾结点后添加 num
|
||||
list.addLast(num);
|
||||
ListNode node = new ListNode(num);
|
||||
// 如果队列为空,则令头、尾结点都指向该结点
|
||||
if (front == null) {
|
||||
front = node;
|
||||
rear = node;
|
||||
// 如果队列不为空,则将该结点添加到尾结点后
|
||||
} else {
|
||||
rear.next = node;
|
||||
rear = node;
|
||||
}
|
||||
queSize++;
|
||||
}
|
||||
|
||||
/* 出队 */
|
||||
public int poll() {
|
||||
int num = peek();
|
||||
// 删除头结点
|
||||
return list.removeFirst();
|
||||
front = front.next;
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 访问队首元素 */
|
||||
public int peek() {
|
||||
return list.getFirst();
|
||||
if (size() == 0)
|
||||
throw new IndexOutOfBoundsException();
|
||||
return front.val;
|
||||
}
|
||||
|
||||
/* 将 List 转化为 Array 并返回 */
|
||||
public Object[] toArray() {
|
||||
return list.toArray();
|
||||
/* 将链表转化为 Array 并返回 */
|
||||
public int[] toArray() {
|
||||
ListNode node = front;
|
||||
int[] res = new int[size()];
|
||||
for (int i = 0; i < res.length; i++) {
|
||||
res[i] = node.val;
|
||||
node = node.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
@ -77,5 +100,6 @@ public class linkedlist_queue {
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
boolean isEmpty = queue.isEmpty();
|
||||
System.out.println("队列是否为空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,18 +7,20 @@
|
||||
package chapter_stack_and_queue;
|
||||
|
||||
import java.util.*;
|
||||
import include.*;
|
||||
|
||||
/* 基于链表实现的栈 */
|
||||
class LinkedListStack {
|
||||
LinkedList<Integer> list;
|
||||
private ListNode stackPeek; // 将头结点作为栈顶
|
||||
private int stkSize = 0; // 栈的长度
|
||||
|
||||
public LinkedListStack() {
|
||||
// 初始化链表
|
||||
list = new LinkedList<>();
|
||||
stackPeek = null;
|
||||
}
|
||||
|
||||
/* 获取栈的长度 */
|
||||
public int size() {
|
||||
return list.size();
|
||||
return stkSize;
|
||||
}
|
||||
|
||||
/* 判断栈是否为空 */
|
||||
@ -28,22 +30,36 @@ class LinkedListStack {
|
||||
|
||||
/* 入栈 */
|
||||
public void push(int num) {
|
||||
list.addLast(num);
|
||||
ListNode node = new ListNode(num);
|
||||
node.next = stackPeek;
|
||||
stackPeek = node;
|
||||
stkSize++;
|
||||
}
|
||||
|
||||
/* 出栈 */
|
||||
public int pop() {
|
||||
return list.removeLast();
|
||||
int num = peek();
|
||||
stackPeek = stackPeek.next;
|
||||
stkSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
public int peek() {
|
||||
return list.getLast();
|
||||
if (size() == 0)
|
||||
throw new IndexOutOfBoundsException();
|
||||
return stackPeek.val;
|
||||
}
|
||||
|
||||
/* 将 List 转化为 Array 并返回 */
|
||||
public Object[] toArray() {
|
||||
return list.toArray();
|
||||
public int[] toArray() {
|
||||
ListNode node = stackPeek;
|
||||
int[] res = new int[size()];
|
||||
for (int i = res.length - 1; i >= 0; i--) {
|
||||
res[i] = node.val;
|
||||
node = node.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
@ -74,5 +90,6 @@ public class linkedlist_stack {
|
||||
|
||||
/* 判断是否为空 */
|
||||
boolean isEmpty = stack.isEmpty();
|
||||
System.out.println("栈是否为空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,5 +35,6 @@ public class queue {
|
||||
|
||||
/* 判断队列是否为空 */
|
||||
boolean isEmpty = queue.isEmpty();
|
||||
System.out.println("队列是否为空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,22 +11,23 @@ import java.util.*;
|
||||
public class stack {
|
||||
public static void main(String[] args) {
|
||||
/* 初始化栈 */
|
||||
Stack<Integer> stack = new Stack<>();
|
||||
// 在 Java 中,推荐将 LinkedList 当作栈来使用
|
||||
LinkedList<Integer> stack = new LinkedList<>();
|
||||
|
||||
/* 元素入栈 */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
stack.addLast(1);
|
||||
stack.addLast(3);
|
||||
stack.addLast(2);
|
||||
stack.addLast(5);
|
||||
stack.addLast(4);
|
||||
System.out.println("栈 stack = " + stack);
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
int peek = stack.peek();
|
||||
int peek = stack.peekLast();
|
||||
System.out.println("栈顶元素 peek = " + peek);
|
||||
|
||||
/* 元素出栈 */
|
||||
int pop = stack.pop();
|
||||
int pop = stack.removeLast();
|
||||
System.out.println("出栈元素 pop = " + pop + ",出栈后 stack = " + stack);
|
||||
|
||||
/* 获取栈的长度 */
|
||||
@ -35,5 +36,6 @@ public class stack {
|
||||
|
||||
/* 判断是否为空 */
|
||||
boolean isEmpty = stack.isEmpty();
|
||||
System.out.println("栈是否为空 = " + isEmpty);
|
||||
}
|
||||
}
|
||||
|
||||
@ -9,6 +9,7 @@ package chapter_tree;
|
||||
import java.util.*;
|
||||
import include.*;
|
||||
|
||||
/* 二叉搜索树 */
|
||||
class BinarySearchTree {
|
||||
private TreeNode root;
|
||||
|
||||
|
||||
@ -91,4 +91,16 @@ public class PrintUtil {
|
||||
showTrunks(p.prev);
|
||||
System.out.print(p.str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Print a hash map
|
||||
* @param <K>
|
||||
* @param <V>
|
||||
* @param map
|
||||
*/
|
||||
public static <K, V> void printHashMap(Map<K, V> map) {
|
||||
for (Map.Entry <K, V> kv: map.entrySet()) {
|
||||
System.out.println(kv.getKey() + " -> " + kv.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -26,6 +26,9 @@ public class TreeNode {
|
||||
* @return
|
||||
*/
|
||||
public static TreeNode arrToTree(Integer[] arr) {
|
||||
if (arr.length == 0)
|
||||
return null;
|
||||
|
||||
TreeNode root = new TreeNode(arr[0]);
|
||||
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
||||
int i = 1;
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
/* 随机访问元素 */
|
||||
function randomAccess(nums){
|
||||
// 在区间 [0, nums.length) 中随机抽取一个数字
|
||||
const random_index = Math.floor(Math.random() * nums.length)
|
||||
const random_index = Math.floor(Math.random() * nums.length)
|
||||
// 获取并返回随机元素
|
||||
random_num = nums[random_index]
|
||||
return random_num
|
||||
|
||||
49
codes/javascript/chapter_sorting/bubble_sort.js
Normal file
49
codes/javascript/chapter_sorting/bubble_sort.js
Normal file
@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: quick_sort.js
|
||||
* Created Time: 2022-12-01
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/* 冒泡排序 */
|
||||
function bubbleSort(nums) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// 内循环:冒泡操作
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 冒泡排序(标志优化)*/
|
||||
function bubbleSortWithFlag(nums) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
let flag = false; // 初始化标志位
|
||||
// 内循环:冒泡操作
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true; // 记录交换元素
|
||||
}
|
||||
}
|
||||
if (!flag) break; // 此轮冒泡未交换任何元素,直接跳出
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
bubbleSort(nums)
|
||||
console.log("排序后数组 nums =", nums)
|
||||
|
||||
var nums1 = [4, 1, 3, 1, 5, 2]
|
||||
bubbleSortWithFlag(nums1)
|
||||
console.log("排序后数组 nums =", nums1)
|
||||
24
codes/javascript/chapter_sorting/insertion_sort.js
Normal file
24
codes/javascript/chapter_sorting/insertion_sort.js
Normal file
@ -0,0 +1,24 @@
|
||||
/**
|
||||
* File: quick_sort.js
|
||||
* Created Time: 2022-12-01
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/* 插入排序 */
|
||||
function insertionSort(nums) {
|
||||
// 外循环:base = nums[1], nums[2], ..., nums[n-1]
|
||||
for (let i = 1; i < nums.length; i++) {
|
||||
let base = nums[i], j = i - 1;
|
||||
// 内循环:将 base 插入到左边的正确位置
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
nums[j + 1] = nums[j]; // 1. 将 nums[j] 向右移动一位
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = base; // 2. 将 base 赋值到正确位置
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
insertionSort(nums)
|
||||
console.log("排序后数组 nums =", nums)
|
||||
51
codes/javascript/chapter_sorting/merge_sort.js
Normal file
51
codes/javascript/chapter_sorting/merge_sort.js
Normal file
@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: quick_sort.js
|
||||
* Created Time: 2022-12-01
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/**
|
||||
* 合并左子数组和右子数组
|
||||
* 左子数组区间 [left, mid]
|
||||
* 右子数组区间 [mid + 1, right]
|
||||
*/
|
||||
function merge(nums, left, mid, right) {
|
||||
// 初始化辅助数组
|
||||
let tmp = nums.slice(left, right + 1);
|
||||
// 左子数组的起始索引和结束索引
|
||||
let leftStart = left - left, leftEnd = mid - left;
|
||||
// 右子数组的起始索引和结束索引
|
||||
let rightStart = mid + 1 - left, rightEnd = right - left;
|
||||
// i, j 分别指向左子数组、右子数组的首元素
|
||||
let i = leftStart, j = rightStart;
|
||||
// 通过覆盖原数组 nums 来合并左子数组和右子数组
|
||||
for (let k = left; k <= right; k++) {
|
||||
// 若 “左子数组已全部合并完”,则选取右子数组元素,并且 j++
|
||||
if (i > leftEnd) {
|
||||
nums[k] = tmp[j++];
|
||||
// 否则,若 “右子数组已全部合并完” 或 “左子数组元素 < 右子数组元素”,则选取左子数组元素,并且 i++
|
||||
} else if (j > rightEnd || tmp[i] <= tmp[j]) {
|
||||
nums[k] = tmp[i++];
|
||||
// 否则,若 “左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
|
||||
} else {
|
||||
nums[k] = tmp[j++];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 归并排序 */
|
||||
function mergeSort(nums, left, right) {
|
||||
// 终止条件
|
||||
if (left >= right) return; // 当子数组长度为 1 时终止递归
|
||||
// 划分阶段
|
||||
let mid = Math.floor((left + right) / 2); // 计算中点
|
||||
mergeSort(nums, left, mid); // 递归左子数组
|
||||
mergeSort(nums, mid + 1, right); // 递归右子数组
|
||||
// 合并阶段
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
var nums = [ 7, 3, 2, 6, 0, 1, 5, 4 ]
|
||||
mergeSort(nums, 0, nums.length - 1)
|
||||
console.log("归并排序完成后 nums =", nums)
|
||||
157
codes/javascript/chapter_sorting/quick_sort.js
Normal file
157
codes/javascript/chapter_sorting/quick_sort.js
Normal file
@ -0,0 +1,157 @@
|
||||
/**
|
||||
* File: quick_sort.js
|
||||
* Created Time: 2022-12-01
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/* 快速排序类 */
|
||||
class QuickSort {
|
||||
/* 元素交换 */
|
||||
swap(nums, i, j) {
|
||||
let tmp = nums[i]
|
||||
nums[i] = nums[j]
|
||||
nums[j] = tmp
|
||||
}
|
||||
|
||||
/* 哨兵划分 */
|
||||
partition(nums, left, right){
|
||||
// 以 nums[left] 作为基准数
|
||||
let i = left, j = right
|
||||
while(i < j){
|
||||
while(i < j && nums[j] >= nums[left]){
|
||||
j -= 1 // 从右向左找首个小于基准数的元素
|
||||
}
|
||||
while(i < j && nums[i] <= nums[left]){
|
||||
i += 1 // 从左向右找首个大于基准数的元素
|
||||
}
|
||||
// 元素交换
|
||||
this.swap(nums, i, j) // 交换这两个元素
|
||||
}
|
||||
this.swap(nums, i, left) // 将基准数交换至两子数组的分界线
|
||||
return i // 返回基准数的索引
|
||||
}
|
||||
|
||||
/* 快速排序 */
|
||||
quickSort(nums, left, right){
|
||||
// 子数组长度为 1 时终止递归
|
||||
if(left >= right) return
|
||||
// 哨兵划分
|
||||
const pivot = this.partition(nums, left, right)
|
||||
// 递归左子数组、右子数组
|
||||
this.quickSort(nums, left, pivot - 1)
|
||||
this.quickSort(nums, pivot + 1, right)
|
||||
}
|
||||
}
|
||||
|
||||
/* 快速排序类(中位基准数优化) */
|
||||
class QuickSortMedian {
|
||||
/* 元素交换 */
|
||||
swap(nums, i, j) {
|
||||
let tmp = nums[i]
|
||||
nums[i] = nums[j]
|
||||
nums[j] = tmp
|
||||
}
|
||||
|
||||
/* 选取三个元素的中位数 */
|
||||
medianThree(nums, left, mid, right) {
|
||||
// 使用了异或操作来简化代码
|
||||
// 异或规则为 0 ^ 0 = 1 ^ 1 = 0, 0 ^ 1 = 1 ^ 0 = 1
|
||||
if ((nums[left] > nums[mid]) ^ (nums[left] > nums[right]))
|
||||
return left;
|
||||
else if ((nums[mid] < nums[left]) ^ (nums[mid] < nums[right]))
|
||||
return mid;
|
||||
else
|
||||
return right;
|
||||
}
|
||||
|
||||
/* 哨兵划分(三数取中值) */
|
||||
partition(nums, left, right) {
|
||||
// 选取三个候选元素的中位数
|
||||
let med = this.medianThree(nums, left, Math.floor((left + right) / 2), right);
|
||||
// 将中位数交换至数组最左端
|
||||
this.swap(nums, left, med);
|
||||
// 以 nums[left] 作为基准数
|
||||
let i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // 从右向左找首个小于基准数的元素
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // 从左向右找首个大于基准数的元素
|
||||
this.swap(nums, i, j); // 交换这两个元素
|
||||
}
|
||||
this.swap(nums, i, left); // 将基准数交换至两子数组的分界线
|
||||
return i; // 返回基准数的索引
|
||||
}
|
||||
|
||||
/* 快速排序 */
|
||||
quickSort(nums, left, right) {
|
||||
// 子数组长度为 1 时终止递归
|
||||
if (left >= right) return;
|
||||
// 哨兵划分
|
||||
const pivot = this.partition(nums, left, right);
|
||||
// 递归左子数组、右子数组
|
||||
this.quickSort(nums, left, pivot - 1);
|
||||
this.quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* 快速排序类(尾递归优化) */
|
||||
class QuickSortTailCall {
|
||||
/* 元素交换 */
|
||||
swap(nums, i, j) {
|
||||
let tmp = nums[i]
|
||||
nums[i] = nums[j]
|
||||
nums[j] = tmp
|
||||
}
|
||||
|
||||
/* 哨兵划分 */
|
||||
partition(nums, left, right) {
|
||||
// 以 nums[left] 作为基准数
|
||||
let i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // 从右向左找首个小于基准数的元素
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // 从左向右找首个大于基准数的元素
|
||||
this.swap(nums, i, j); // 交换这两个元素
|
||||
}
|
||||
this.swap(nums, i, left); // 将基准数交换至两子数组的分界线
|
||||
return i; // 返回基准数的索引
|
||||
}
|
||||
|
||||
/* 快速排序(尾递归优化) */
|
||||
quickSort(nums, left, right) {
|
||||
// 子数组长度为 1 时终止
|
||||
while (left < right) {
|
||||
// 哨兵划分操作
|
||||
let pivot = this.partition(nums, left, right);
|
||||
// 对两个子数组中较短的那个执行快排
|
||||
if (pivot - left < right - pivot) {
|
||||
this.quickSort(nums, left, pivot - 1); // 递归排序左子数组
|
||||
left = pivot + 1; // 剩余待排序区间为 [pivot + 1, right]
|
||||
} else {
|
||||
this.quickSort(nums, pivot + 1, right); // 递归排序右子数组
|
||||
right = pivot - 1; // 剩余待排序区间为 [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* 快速排序 */
|
||||
var nums = [4, 1, 3, 1, 5, 2]
|
||||
var quickSort = new QuickSort()
|
||||
quickSort.quickSort(nums, 0, nums.length - 1)
|
||||
console.log("快速排序完成后 nums =", nums)
|
||||
|
||||
/* 快速排序(中位基准数优化) */
|
||||
nums1 = [4, 1, 3, 1, 5,2]
|
||||
var quickSortMedian = new QuickSort()
|
||||
quickSortMedian.quickSort(nums1, 0, nums1.length - 1)
|
||||
console.log("快速排序(中位基准数优化)完成后 nums =", nums1)
|
||||
|
||||
/* 快速排序(尾递归优化) */
|
||||
nums2 = [4, 1, 3, 1, 5, 2]
|
||||
var quickSortTailCall = new QuickSort()
|
||||
quickSortTailCall.quickSort(nums2, 0, nums2.length - 1)
|
||||
console.log("快速排序(尾递归优化)完成后 nums =", nums2)
|
||||
34
codes/javascript/chapter_stack_and_queue/stack.js
Normal file
34
codes/javascript/chapter_stack_and_queue/stack.js
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* File: stack.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* 初始化栈 */
|
||||
// Javascript 没有内置的栈类,可以把 Array 当作栈来使用
|
||||
const stack = [];
|
||||
|
||||
/* 元素入栈 */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
console.log("栈 stack =", stack)
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
const peek = stack[stack.length - 1];
|
||||
console.log("栈顶元素 peek =", peek)
|
||||
|
||||
/* 元素出栈 */
|
||||
const pop = stack.pop();
|
||||
console.log("出栈元素 pop =", pop)
|
||||
console.log("出栈后 stack =", stack)
|
||||
|
||||
/* 获取栈的长度 */
|
||||
const size = stack.length;
|
||||
console.log("栈的长度 size =", size)
|
||||
|
||||
/* 判断是否为空 */
|
||||
const is_empty = stack.length === 0;
|
||||
console.log("栈是否为空 =", is_empty)
|
||||
146
codes/javascript/chapter_tree/binary_search_tree.js
Normal file
146
codes/javascript/chapter_tree/binary_search_tree.js
Normal file
@ -0,0 +1,146 @@
|
||||
/**
|
||||
* File: binary_tree.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
const Tree = require("../include/TreeNode");
|
||||
const { printTree } = require("../include/PrintUtil");
|
||||
|
||||
/* 二叉搜索树 */
|
||||
var root;
|
||||
|
||||
function BinarySearchTree(nums) {
|
||||
nums.sort((a,b) => { return a-b }); // 排序数组
|
||||
root = buildTree(nums, 0, nums.length - 1); // 构建二叉搜索树
|
||||
}
|
||||
|
||||
/* 获取二叉树根结点 */
|
||||
function getRoot() {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 构建二叉搜索树 */
|
||||
function buildTree(nums, i, j) {
|
||||
if (i > j) return null;
|
||||
// 将数组中间结点作为根结点
|
||||
let mid = Math.floor((i + j) / 2);
|
||||
let root = new Tree.TreeNode(nums[mid]);
|
||||
// 递归建立左子树和右子树
|
||||
root.left = buildTree(nums, i, mid - 1);
|
||||
root.right = buildTree(nums, mid + 1, j);
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 查找结点 */
|
||||
function search(num) {
|
||||
let cur = root;
|
||||
// 循环查找,越过叶结点后跳出
|
||||
while (cur !== null) {
|
||||
// 目标结点在 root 的右子树中
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// 目标结点在 root 的左子树中
|
||||
else if (cur.val > num) cur = cur.left;
|
||||
// 找到目标结点,跳出循环
|
||||
else break;
|
||||
}
|
||||
// 返回目标结点
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* 插入结点 */
|
||||
function insert(num) {
|
||||
// 若树为空,直接提前返回
|
||||
if (root === null) return null;
|
||||
let cur = root, pre = null;
|
||||
// 循环查找,越过叶结点后跳出
|
||||
while (cur !== null) {
|
||||
// 找到重复结点,直接返回
|
||||
if (cur.val === num) return null;
|
||||
pre = cur;
|
||||
// 插入位置在 root 的右子树中
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// 插入位置在 root 的左子树中
|
||||
else cur = cur.left;
|
||||
}
|
||||
// 插入结点 val
|
||||
let node = new Tree.TreeNode(num);
|
||||
if (pre.val < num) pre.right = node;
|
||||
else pre.left = node;
|
||||
return node;
|
||||
}
|
||||
|
||||
/* 删除结点 */
|
||||
function remove(num) {
|
||||
// 若树为空,直接提前返回
|
||||
if (root === null) return null;
|
||||
let cur = root, pre = null;
|
||||
// 循环查找,越过叶结点后跳出
|
||||
while (cur !== null) {
|
||||
// 找到待删除结点,跳出循环
|
||||
if (cur.val === num) break;
|
||||
pre = cur;
|
||||
// 待删除结点在 root 的右子树中
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// 待删除结点在 root 的左子树中
|
||||
else cur = cur.left;
|
||||
}
|
||||
// 若无待删除结点,则直接返回
|
||||
if (cur === null) return null;
|
||||
// 子结点数量 = 0 or 1
|
||||
if (cur.left === null || cur.right === null) {
|
||||
// 当子结点数量 = 0 / 1 时, child = null / 该子结点
|
||||
let child = cur.left !== null ? cur.left : cur.right;
|
||||
// 删除结点 cur
|
||||
if (pre.left === cur) pre.left = child;
|
||||
else pre.right = child;
|
||||
}
|
||||
// 子结点数量 = 2
|
||||
else {
|
||||
// 获取中序遍历中 cur 的下一个结点
|
||||
let nex = min(cur.right);
|
||||
let tmp = nex.val;
|
||||
// 递归删除结点 nex
|
||||
remove(nex.val);
|
||||
// 将 nex 的值复制给 cur
|
||||
cur.val = tmp;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* 获取最小结点 */
|
||||
function min(root) {
|
||||
if (root === null) return root;
|
||||
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
||||
while (root.left !== null) {
|
||||
root = root.left;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* 初始化二叉搜索树 */
|
||||
var nums = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ];
|
||||
BinarySearchTree(nums)
|
||||
console.log("\n初始化的二叉树为\n");
|
||||
printTree(getRoot());
|
||||
|
||||
/* 查找结点 */
|
||||
let node = search(5);
|
||||
console.log("\n查找到的结点对象为 " + node + ",结点值 = " + node.val);
|
||||
|
||||
/* 插入结点 */
|
||||
node = insert(16);
|
||||
console.log("\n插入结点 16 后,二叉树为\n");
|
||||
printTree(getRoot());
|
||||
|
||||
/* 删除结点 */
|
||||
remove(1);
|
||||
console.log("\n删除结点 1 后,二叉树为\n");
|
||||
printTree(getRoot());
|
||||
remove(2);
|
||||
console.log("\n删除结点 2 后,二叉树为\n");
|
||||
printTree(getRoot());
|
||||
remove(4);
|
||||
console.log("\n删除结点 4 后,二叉树为\n");
|
||||
printTree(getRoot());
|
||||
35
codes/javascript/chapter_tree/binary_tree.js
Normal file
35
codes/javascript/chapter_tree/binary_tree.js
Normal file
@ -0,0 +1,35 @@
|
||||
/**
|
||||
* File: binary_tree.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
const Tree = require("../include/TreeNode");
|
||||
const { printTree } = require("../include/PrintUtil");
|
||||
|
||||
/* 初始化二叉树 */
|
||||
// 初始化结点
|
||||
let n1 = new Tree.TreeNode(1),
|
||||
n2 = new Tree.TreeNode(2),
|
||||
n3 = new Tree.TreeNode(3),
|
||||
n4 = new Tree.TreeNode(4),
|
||||
n5 = new Tree.TreeNode(5);
|
||||
// 构建引用指向(即指针)
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
console.log("\n初始化二叉树\n")
|
||||
printTree(n1)
|
||||
|
||||
/* 插入与删除结点 */
|
||||
let P = new Tree.TreeNode(0);
|
||||
// 在 n1 -> n2 中间插入结点 P
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
console.log("\n插入结点 P 后\n");
|
||||
printTree(n1);
|
||||
// 删除结点 P
|
||||
n1.left = n2;
|
||||
console.log("\n删除结点 P 后\n");
|
||||
printTree(n1);
|
||||
37
codes/javascript/chapter_tree/binary_tree_bfs.js
Normal file
37
codes/javascript/chapter_tree/binary_tree_bfs.js
Normal file
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: binary_tree.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
const { arrToTree } = require("../include/TreeNode");
|
||||
const { printTree } = require("../include/PrintUtil");
|
||||
|
||||
/* 层序遍历 */
|
||||
function hierOrder(root) {
|
||||
// 初始化队列,加入根结点
|
||||
let queue = [root];
|
||||
// 初始化一个列表,用于保存遍历序列
|
||||
let list = [];
|
||||
while (queue.length) {
|
||||
let node = queue.shift(); // 队列出队
|
||||
list.push(node.val); // 保存结点
|
||||
if (node.left)
|
||||
queue.push(node.left); // 左子结点入队
|
||||
if (node.right)
|
||||
queue.push(node.right); // 右子结点入队
|
||||
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
var root = arrToTree([1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null ]);
|
||||
console.log("\n初始化二叉树\n");
|
||||
printTree(root);
|
||||
|
||||
/* 层序遍历 */
|
||||
let list = hierOrder(root);
|
||||
console.log("\n层序遍历的结点打印序列 = " + list);
|
||||
61
codes/javascript/chapter_tree/binary_tree_dfs.js
Normal file
61
codes/javascript/chapter_tree/binary_tree_dfs.js
Normal file
@ -0,0 +1,61 @@
|
||||
/**
|
||||
* File: binary_tree.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
const { arrToTree } = require("../include/TreeNode");
|
||||
const { printTree } = require("../include/PrintUtil");
|
||||
|
||||
// 初始化列表,用于存储遍历序列
|
||||
var list = []
|
||||
|
||||
/* 前序遍历 */
|
||||
function preOrder(root){
|
||||
if (root === null) return;
|
||||
// 访问优先级:根结点 -> 左子树 -> 右子树
|
||||
list.push(root.val);
|
||||
preOrder(root.left);
|
||||
preOrder(root.right);
|
||||
}
|
||||
|
||||
/* 中序遍历 */
|
||||
function inOrder(root) {
|
||||
if (root === null) return;
|
||||
// 访问优先级:左子树 -> 根结点 -> 右子树
|
||||
inOrder(root.left);
|
||||
list.push(root.val);
|
||||
inOrder(root.right);
|
||||
}
|
||||
|
||||
/* 后序遍历 */
|
||||
function postOrder(root) {
|
||||
if (root === null) return;
|
||||
// 访问优先级:左子树 -> 右子树 -> 根结点
|
||||
postOrder(root.left);
|
||||
postOrder(root.right);
|
||||
list.push(root.val);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* 初始化二叉树 */
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
var root = arrToTree([1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null]);
|
||||
console.log("\n初始化二叉树\n");
|
||||
printTree(root);
|
||||
|
||||
/* 前序遍历 */
|
||||
list.length = 0;
|
||||
preOrder(root);
|
||||
console.log("\n前序遍历的结点打印序列 = " + list);
|
||||
|
||||
/* 中序遍历 */
|
||||
list.length = 0;
|
||||
inOrder(root);
|
||||
console.log("\n中序遍历的结点打印序列 = " + list);
|
||||
|
||||
/* 后序遍历 */
|
||||
list.length = 0;
|
||||
postOrder(root);
|
||||
console.log("\n后序遍历的结点打印序列 = " + list);
|
||||
|
||||
88
codes/javascript/include/PrintUtil.js
Normal file
88
codes/javascript/include/PrintUtil.js
Normal file
@ -0,0 +1,88 @@
|
||||
/**
|
||||
* File: PrintUtil.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
function Trunk(prev, str) {
|
||||
this.prev = prev;
|
||||
this.str = str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Print a linked list
|
||||
* @param head
|
||||
*/
|
||||
function printLinkedList(head) {
|
||||
let list = [];
|
||||
while (head !== null) {
|
||||
list.push(head.val.toString());
|
||||
head = head.next;
|
||||
}
|
||||
console.log(list.join(" -> "));
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface of the tree printer
|
||||
* This tree printer is borrowed from TECHIE DELIGHT
|
||||
* https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
* @param root
|
||||
*/
|
||||
function printTree(root) {
|
||||
printTree(root, null, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Print a binary tree
|
||||
* @param root
|
||||
* @param prev
|
||||
* @param isLeft
|
||||
*/
|
||||
function printTree(root, prev, isLeft) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
let prev_str = " ";
|
||||
let 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);
|
||||
console.log(" " + root.val);
|
||||
|
||||
if (prev) {
|
||||
prev.str = prev_str;
|
||||
}
|
||||
trunk.str = " |";
|
||||
|
||||
printTree(root.left, trunk, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to print branches of the binary tree
|
||||
* @param p
|
||||
*/
|
||||
function showTrunks(p) {
|
||||
if (!p) {
|
||||
return;
|
||||
}
|
||||
|
||||
showTrunks(p.prev);
|
||||
console.log(p.str);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
printTree,
|
||||
printLinkedList,
|
||||
}
|
||||
47
codes/javascript/include/TreeNode.js
Normal file
47
codes/javascript/include/TreeNode.js
Normal file
@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: TreeNode.js
|
||||
* Created Time: 2022-12-04
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
*/
|
||||
function TreeNode(val, left, right) {
|
||||
this.val = (val === undefined ? 0 : val) // 结点值
|
||||
this.left = (left === undefined ? null : left) // 左子结点指针
|
||||
this.right = (right === undefined ? null : right) // 右子结点指针
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a binary tree with an array
|
||||
* @param arr
|
||||
* @return
|
||||
*/
|
||||
function arrToTree(arr) {
|
||||
if (arr.length === 0)
|
||||
return null;
|
||||
|
||||
let root = new TreeNode(arr[0]);
|
||||
let queue = [root]
|
||||
let i = 1;
|
||||
while(queue.length) {
|
||||
let node = queue.shift();
|
||||
if(arr[i] !== null) {
|
||||
node.left = new TreeNode(arr[i]);
|
||||
queue.push(node.left);
|
||||
}
|
||||
i++;
|
||||
if(arr[i] !== null) {
|
||||
node.right = new TreeNode(arr[i]);
|
||||
queue.push(node.right);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TreeNode,
|
||||
arrToTree,
|
||||
}
|
||||
@ -33,7 +33,7 @@ if __name__ == "__main__":
|
||||
list.append(2)
|
||||
list.append(5)
|
||||
list.append(4)
|
||||
print("添加元素后 list = ", list)
|
||||
print("添加元素后 list =", list)
|
||||
|
||||
""" 中间插入元素 """
|
||||
list.insert(3, 6)
|
||||
|
||||
@ -12,64 +12,65 @@ from include import *
|
||||
class MyList:
|
||||
""" 构造函数 """
|
||||
def __init__(self):
|
||||
self._capacity = 10 # 列表容量
|
||||
self._nums = [0] * self._capacity # 数组(存储列表元素)
|
||||
self._size = 0 # 列表长度(即当前元素数量)
|
||||
self._extend_ratio = 2 # 每次列表扩容的倍数
|
||||
self.__capacity = 10 # 列表容量
|
||||
self.__nums = [0] * self.__capacity # 数组(存储列表元素)
|
||||
self.__size = 0 # 列表长度(即当前元素数量)
|
||||
self.__extend_ratio = 2 # 每次列表扩容的倍数
|
||||
|
||||
""" 获取列表长度(即当前元素数量) """
|
||||
def size(self):
|
||||
return self._size
|
||||
return self.__size
|
||||
|
||||
""" 获取列表容量 """
|
||||
def capacity(self):
|
||||
return self._capacity
|
||||
return self.__capacity
|
||||
|
||||
""" 访问元素 """
|
||||
def get(self, index):
|
||||
# 索引如果越界则抛出异常,下同
|
||||
assert index < self._size, "索引越界"
|
||||
return self._nums[index]
|
||||
assert index < self.__size, "索引越界"
|
||||
return self.__nums[index]
|
||||
|
||||
""" 更新元素 """
|
||||
def set(self, num, index):
|
||||
assert index < self._size, "索引越界"
|
||||
self._nums[index] = num
|
||||
assert index < self.__size, "索引越界"
|
||||
self.__nums[index] = num
|
||||
|
||||
""" 中间插入元素 """
|
||||
""" 中间插入(尾部添加)元素 """
|
||||
def add(self, num, index=-1):
|
||||
assert index < self._size, "索引越界"
|
||||
assert index < self.__size, "索引越界"
|
||||
# 若不指定索引 index ,则向数组尾部添加元素
|
||||
if index == -1:
|
||||
index = self._size
|
||||
index = self.__size
|
||||
# 元素数量超出容量时,触发扩容机制
|
||||
if self._size == self.capacity():
|
||||
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
|
||||
for j in range(self.__size - 1, index - 1, -1):
|
||||
self.__nums[j + 1] = self.__nums[j]
|
||||
self.__nums[index] = num
|
||||
# 更新元素数量
|
||||
self._size += 1
|
||||
self.__size += 1
|
||||
|
||||
""" 删除元素 """
|
||||
def remove(self, index):
|
||||
assert index < self._size, "索引越界"
|
||||
assert index < self.__size, "索引越界"
|
||||
# 索引 i 之后的元素都向前移动一位
|
||||
for j in range(index, self._size - 1):
|
||||
self._nums[j] = self._nums[j + 1]
|
||||
for j in range(index, self.__size - 1):
|
||||
self.__nums[j] = self.__nums[j + 1]
|
||||
# 更新元素数量
|
||||
self._size -= 1
|
||||
self.__size -= 1
|
||||
|
||||
""" 列表扩容 """
|
||||
def extend_capacity(self):
|
||||
# 新建一个长度为 self._size 的数组,并将原数组拷贝到新数组
|
||||
self._nums = self._nums + [0] * self.capacity() * (self._extend_ratio - 1)
|
||||
# 新建一个长度为 self.__size 的数组,并将原数组拷贝到新数组
|
||||
self.__nums = self.__nums + [0] * self.capacity() * (self.__extend_ratio - 1)
|
||||
# 更新列表容量
|
||||
self._capacity = len(self._nums)
|
||||
self.__capacity = len(self.__nums)
|
||||
|
||||
""" 返回有效长度的列表 """
|
||||
def to_array(self):
|
||||
return self._nums[:self._size]
|
||||
return self.__nums[:self.__size]
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
|
||||
@ -1,10 +1,53 @@
|
||||
'''
|
||||
File: binary_search.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-26
|
||||
Author: timi (xisunyy@163.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 二分查找(双闭区间) """
|
||||
def binary_search(nums, target):
|
||||
# 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
|
||||
i, j = 0, len(nums) - 1
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # 计算中点索引 m
|
||||
if nums[m] < target: # 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1
|
||||
elif nums[m] > target: # 此情况说明 target 在区间 [i, m-1] 中
|
||||
j = m - 1
|
||||
else:
|
||||
return m # 找到目标元素,返回其索引
|
||||
return -1 # 未找到目标元素,返回 -1
|
||||
|
||||
|
||||
""" 二分查找(左闭右开) """
|
||||
def binary_search1(nums, target):
|
||||
# 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
i, j = 0, len(nums)
|
||||
# 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while i < j:
|
||||
m = (i + j) // 2 # 计算中点索引 m
|
||||
if nums[m] < target: # 此情况说明 target 在区间 [m+1, j) 中
|
||||
i = m + 1
|
||||
elif nums[m] > target: # 此情况说明 target 在区间 [i, m) 中
|
||||
j = m
|
||||
else: # 找到目标元素,返回其索引
|
||||
return m
|
||||
return -1 # 未找到目标元素,返回 -1
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == '__main__':
|
||||
target = 6
|
||||
nums = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92]
|
||||
|
||||
# 二分查找(双闭区间)
|
||||
index = binary_search(nums, target)
|
||||
print("目标元素 6 的索引 = ", index)
|
||||
|
||||
# 二分查找(左闭右开)
|
||||
index = binary_search1(nums, target)
|
||||
print("目标元素 6 的索引 = ", index)
|
||||
|
||||
@ -1,10 +1,45 @@
|
||||
'''
|
||||
File: hashing_search.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-26
|
||||
Author: timi (xisunyy@163.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 哈希查找(数组) """
|
||||
def hashing_search(mapp, target):
|
||||
# 哈希表的 key: 目标元素,value: 索引
|
||||
# 若哈希表中无此 key ,返回 -1
|
||||
return mapp.get(target, -1)
|
||||
|
||||
""" 哈希查找(链表) """
|
||||
def hashing_search1(mapp, target):
|
||||
# 哈希表的 key: 目标元素,value: 结点对象
|
||||
# 若哈希表中无此 key ,返回 -1
|
||||
return mapp.get(target, -1)
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == '__main__':
|
||||
target = 3
|
||||
|
||||
# 哈希查找(数组)
|
||||
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
# 初始化哈希表
|
||||
mapp = {}
|
||||
for i in range(len(nums)):
|
||||
mapp[nums[i]] = i # key: 元素,value: 索引
|
||||
index = hashing_search(mapp, target)
|
||||
print("目标元素 3 的索引 =", index)
|
||||
|
||||
# 哈希查找(链表)
|
||||
head = list_to_linked_list(nums)
|
||||
# 初始化哈希表
|
||||
map1 = {}
|
||||
while head:
|
||||
map1[head.val] = head # key: 结点值,value: 结点
|
||||
head = head.next
|
||||
node = hashing_search1(map1, target)
|
||||
print("目标结点值 3 的对应结点对象为", node)
|
||||
|
||||
@ -1,10 +1,41 @@
|
||||
'''
|
||||
File: linear_search.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-26
|
||||
Author: timi (xisunyy@163.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 线性查找(数组) """
|
||||
def linear_search(nums, target):
|
||||
# 遍历数组
|
||||
for i in range(len(nums)):
|
||||
if nums[i] == target: # 找到目标元素,返回其索引
|
||||
return i
|
||||
return -1 # 未找到目标元素,返回 -1
|
||||
|
||||
""" 线性查找(链表) """
|
||||
def linear_search1(head, target):
|
||||
# 遍历链表
|
||||
while head:
|
||||
if head.val == target: # 找到目标结点,返回之
|
||||
return head
|
||||
head = head.next
|
||||
return None # 未找到目标结点,返回 None
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == '__main__':
|
||||
target = 3
|
||||
|
||||
# 在数组中执行线性查找
|
||||
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
index = linear_search(nums, target)
|
||||
print("目标元素 3 的索引 =", index)
|
||||
|
||||
# 在链表中执行线性查找
|
||||
head = list_to_linked_list(nums)
|
||||
node = linear_search1(head, target)
|
||||
print("目标结点值 3 的对应结点对象为", node)
|
||||
|
||||
@ -25,4 +25,4 @@ def insertion_sort(nums):
|
||||
if __name__ == '__main__':
|
||||
nums = [4, 1, 3, 1, 5, 2]
|
||||
insertion_sort(nums)
|
||||
print("排序后数组 nums = ", nums)
|
||||
print("排序后数组 nums =", nums)
|
||||
|
||||
@ -1,10 +1,108 @@
|
||||
'''
|
||||
File: array_queue.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-12-01
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
import os.path as osp
|
||||
import sys
|
||||
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 基于环形数组实现的队列 """
|
||||
class ArrayQueue:
|
||||
def __init__(self, size):
|
||||
self.__nums = [0] * size # 用于存储队列元素的数组
|
||||
self.__front = 0 # 头指针,指向队首
|
||||
self.__rear = 0 # 尾指针,指向队尾 + 1
|
||||
|
||||
""" 获取队列的容量 """
|
||||
def capacity(self):
|
||||
return len(self.__nums)
|
||||
|
||||
""" 获取队列的长度 """
|
||||
def size(self):
|
||||
# 由于将数组看作为环形,可能 rear < front ,因此需要取余数
|
||||
return (self.capacity() + self.__rear - self.__front) % self.capacity()
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
def is_empty(self):
|
||||
return (self.__rear - self.__front) == 0
|
||||
|
||||
""" 入队 """
|
||||
def push(self, val):
|
||||
if self.size() == self.capacity():
|
||||
print("队列已满")
|
||||
return False
|
||||
# 尾结点后添加 num
|
||||
self.__nums[self.__rear] = val
|
||||
# 尾指针向后移动一位,越过尾部后返回到数组头部
|
||||
self.__rear = (self.__rear + 1) % self.capacity()
|
||||
|
||||
""" 出队 """
|
||||
def poll(self):
|
||||
# 删除头结点
|
||||
num = self.peek()
|
||||
# 队头指针向后移动一位,若越过尾部则返回到数组头部
|
||||
self.__front = (self.__front + 1) % self.capacity()
|
||||
return num
|
||||
|
||||
""" 访问队首元素 """
|
||||
def peek(self):
|
||||
# 删除头结点
|
||||
if self.is_empty():
|
||||
print("队列为空")
|
||||
return False
|
||||
return self.__nums[self.__front]
|
||||
|
||||
""" 访问指定位置元素 """
|
||||
def get(self, index):
|
||||
if index >= self.size():
|
||||
print("索引越界")
|
||||
return False
|
||||
return self.__nums[(self.__front + index) % self.capacity()]
|
||||
|
||||
""" 返回列表用于打印 """
|
||||
def to_list(self):
|
||||
res = [0] * self.size()
|
||||
j = self.__front
|
||||
for i in range(self.size()):
|
||||
res[i] = self.__nums[(j % self.capacity())]
|
||||
j += 1
|
||||
return res
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
queue = ArrayQueue(10)
|
||||
|
||||
""" 元素入队 """
|
||||
queue.push(1)
|
||||
queue.push(3)
|
||||
queue.push(2)
|
||||
queue.push(5)
|
||||
queue.push(4)
|
||||
print("队列 queue =", queue.to_list())
|
||||
|
||||
""" 访问队首元素 """
|
||||
peek = queue.peek()
|
||||
print("队首元素 peek =", peek)
|
||||
|
||||
""" 访问索引 index 处元素 """
|
||||
num = queue.get(3)
|
||||
print("队列索引 3 处的元素为 num =", num)
|
||||
|
||||
""" 元素出队 """
|
||||
poll = queue.poll()
|
||||
print("出队元素 poll =", poll)
|
||||
print("出队后 queue =", queue.to_list())
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = queue.size()
|
||||
print("队列长度 size =", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = queue.is_empty()
|
||||
print("队列是否为空 =", is_empty)
|
||||
|
||||
@ -1,10 +1,77 @@
|
||||
'''
|
||||
File: array_stack.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-29
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 基于数组实现的栈 """
|
||||
class ArrayStack:
|
||||
def __init__(self):
|
||||
self.__stack = []
|
||||
|
||||
""" 获取栈的长度 """
|
||||
def size(self):
|
||||
return len(self.__stack)
|
||||
|
||||
""" 判断栈是否为空 """
|
||||
def is_empty(self):
|
||||
return self.__stack == []
|
||||
|
||||
""" 入栈 """
|
||||
def push(self, item):
|
||||
self.__stack.append(item)
|
||||
|
||||
""" 出栈 """
|
||||
def pop(self):
|
||||
return self.__stack.pop()
|
||||
|
||||
""" 访问栈顶元素 """
|
||||
def peek(self):
|
||||
return self.__stack[-1]
|
||||
|
||||
""" 访问索引 index 处元素 """
|
||||
def get(self, index):
|
||||
return self.__stack[index]
|
||||
|
||||
""" 返回列表用于打印 """
|
||||
def to_list(self):
|
||||
return self.__stack
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化栈 """
|
||||
stack = ArrayStack()
|
||||
|
||||
""" 元素入栈 """
|
||||
stack.push(1)
|
||||
stack.push(3)
|
||||
stack.push(2)
|
||||
stack.push(5)
|
||||
stack.push(4)
|
||||
print("栈 stack =", stack.to_list())
|
||||
|
||||
""" 访问栈顶元素 """
|
||||
peek = stack.peek()
|
||||
print("栈顶元素 peek =", peek)
|
||||
|
||||
""" 访问索引 index 处元素 """
|
||||
num = stack.get(3)
|
||||
print("栈索引 3 处的元素为 num =", num)
|
||||
|
||||
""" 元素出栈 """
|
||||
pop = stack.pop()
|
||||
print("出栈元素 pop =", pop)
|
||||
print("出栈后 stack =", stack.to_list())
|
||||
|
||||
""" 获取栈的长度 """
|
||||
size = stack.size()
|
||||
print("栈的长度 size =", size)
|
||||
|
||||
""" 判断是否为空 """
|
||||
is_empty = stack.is_empty()
|
||||
print("栈是否为空 =", is_empty)
|
||||
|
||||
@ -1,10 +1,49 @@
|
||||
'''
|
||||
File: deque.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-29
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
import os.path as osp
|
||||
import sys
|
||||
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
from collections import deque
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化双向队列 """
|
||||
duque = deque()
|
||||
|
||||
""" 元素入队 """
|
||||
duque.append(2) # 添加至队尾
|
||||
duque.append(5)
|
||||
duque.append(4)
|
||||
duque.appendleft(3) # 添加至队首
|
||||
duque.appendleft(1)
|
||||
print("双向队列 duque =", duque)
|
||||
|
||||
""" 访问元素 """
|
||||
front = duque[0] # 队首元素
|
||||
print("队首元素 front =", front)
|
||||
rear = duque[-1] # 队尾元素
|
||||
print("队尾元素 rear =", rear)
|
||||
|
||||
""" 元素出队 """
|
||||
pop_front = duque.popleft() # 队首元素出队
|
||||
print("队首出队元素 pop_front =", pop_front)
|
||||
print("队首出队后 duque =", duque)
|
||||
pop_rear = duque.pop() # 队尾元素出队
|
||||
print("队尾出队元素 pop_rear =", pop_rear)
|
||||
print("队尾出队后 duque =", duque)
|
||||
|
||||
""" 获取双向队列的长度 """
|
||||
size = len(duque)
|
||||
print("双向队列长度 size =", size)
|
||||
|
||||
""" 判断双向队列是否为空 """
|
||||
is_empty = len(duque) == 0
|
||||
print("双向队列是否为空 =", is_empty)
|
||||
|
||||
@ -1,10 +1,95 @@
|
||||
'''
|
||||
File: linkedlist_queue.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-12-01
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
import os.path as osp
|
||||
import sys
|
||||
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 基于链表实现的队列 """
|
||||
class LinkedListQueue:
|
||||
def __init__(self):
|
||||
self.__front = None # 头结点 front
|
||||
self.__rear = None # 尾结点 rear
|
||||
self.__size = 0
|
||||
|
||||
""" 获取队列的长度 """
|
||||
def size(self):
|
||||
return self.__size
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
def is_empty(self):
|
||||
return not self.__front
|
||||
|
||||
""" 入队 """
|
||||
def push(self, num):
|
||||
# 尾结点后添加 num
|
||||
node = ListNode(num)
|
||||
# 如果队列为空,则令头、尾结点都指向该结点
|
||||
if self.__front == 0:
|
||||
self.__front = node
|
||||
self.__rear = node
|
||||
# 如果队列不为空,则将该结点添加到尾结点后
|
||||
else:
|
||||
self.__rear.next = node
|
||||
self.__rear = node
|
||||
self.__size += 1
|
||||
|
||||
""" 出队 """
|
||||
def poll(self):
|
||||
num = self.peek()
|
||||
# 删除头结点
|
||||
self.__front = self.__front.next
|
||||
self.__size -= 1
|
||||
return num
|
||||
|
||||
""" 访问队首元素 """
|
||||
def peek(self):
|
||||
if self.size() == 0:
|
||||
print("队列为空")
|
||||
return False
|
||||
return self.__front.val
|
||||
|
||||
""" 转化为列表用于打印 """
|
||||
def to_list(self):
|
||||
queue = []
|
||||
temp = self.__front
|
||||
while temp:
|
||||
queue.append(temp.val)
|
||||
temp = temp.next
|
||||
return queue
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
queue = LinkedListQueue()
|
||||
|
||||
""" 元素入队 """
|
||||
queue.push(1)
|
||||
queue.push(3)
|
||||
queue.push(2)
|
||||
queue.push(5)
|
||||
queue.push(4)
|
||||
print("队列 queue =", queue.to_list())
|
||||
|
||||
""" 访问队首元素 """
|
||||
peek = queue.peek()
|
||||
print("队首元素 front =", peek)
|
||||
|
||||
""" 元素出队 """
|
||||
pop_front = queue.poll()
|
||||
print("出队元素 poll =", pop_front)
|
||||
print("出队后 queue =", queue.to_list())
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = queue.size()
|
||||
print("队列长度 size =", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = queue.is_empty()
|
||||
print("队列是否为空 =", is_empty)
|
||||
|
||||
@ -1,10 +1,84 @@
|
||||
'''
|
||||
File: linkedlist_stack.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-29
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
""" 基于链表实现的栈 """
|
||||
class LinkedListStack:
|
||||
def __init__(self):
|
||||
self.__peek = None
|
||||
self.__size = 0
|
||||
|
||||
""" 获取栈的长度 """
|
||||
def size(self):
|
||||
return self.__size
|
||||
|
||||
""" 判断栈是否为空 """
|
||||
def is_empty(self):
|
||||
return not self.__peek
|
||||
|
||||
""" 入栈 """
|
||||
def push(self, val):
|
||||
node = ListNode(val)
|
||||
node.next = self.__peek
|
||||
self.__peek = node
|
||||
self.__size += 1
|
||||
|
||||
""" 出栈 """
|
||||
def pop(self):
|
||||
num = self.peek()
|
||||
self.__peek = self.__peek.next
|
||||
self.__size -= 1
|
||||
return num
|
||||
|
||||
""" 访问栈顶元素 """
|
||||
def peek(self):
|
||||
# 判空处理
|
||||
if not self.__peek: return None
|
||||
return self.__peek.val
|
||||
|
||||
""" 转化为列表用于打印 """
|
||||
def to_list(self):
|
||||
arr = []
|
||||
node = self.__peek
|
||||
while node:
|
||||
arr.append(node.val)
|
||||
node = node.next
|
||||
arr.reverse()
|
||||
return arr
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化栈 """
|
||||
stack = LinkedListStack()
|
||||
|
||||
""" 元素入栈 """
|
||||
stack.push(1)
|
||||
stack.push(3)
|
||||
stack.push(2)
|
||||
stack.push(5)
|
||||
stack.push(4)
|
||||
print("栈 stack =", stack.to_list())
|
||||
|
||||
""" 访问栈顶元素 """
|
||||
peek = stack.peek()
|
||||
print("栈顶元素 peek =", peek)
|
||||
|
||||
""" 元素出栈 """
|
||||
pop = stack.pop()
|
||||
print("出栈元素 pop =", pop)
|
||||
print("出栈后 stack =", stack.to_list())
|
||||
|
||||
""" 获取栈的长度 """
|
||||
size = stack.size()
|
||||
print("栈的长度 size =", size)
|
||||
|
||||
""" 判断是否为空 """
|
||||
is_empty = stack.is_empty()
|
||||
print("栈是否为空 =", is_empty)
|
||||
|
||||
@ -1,10 +1,44 @@
|
||||
'''
|
||||
File: queue.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
File: que.py
|
||||
Created Time: 2022-11-29
|
||||
Author: Peng Chen (pengchzn@gmail.com)
|
||||
'''
|
||||
|
||||
import sys, os.path as osp
|
||||
import os.path as osp
|
||||
import sys
|
||||
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
|
||||
|
||||
""" Driver Code """
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
# 在 Python 中,我们一般将双向队列类 deque 看左队列使用
|
||||
# 虽然 queue.Queue() 是纯正的队列类,但不太好用,因此不建议
|
||||
que = collections.deque()
|
||||
|
||||
""" 元素入队 """
|
||||
que.append(1)
|
||||
que.append(3)
|
||||
que.append(2)
|
||||
que.append(5)
|
||||
que.append(4)
|
||||
print("队列 que =", que)
|
||||
|
||||
""" 访问队首元素 """
|
||||
front = que[0];
|
||||
print("队首元素 front =", front);
|
||||
|
||||
""" 元素出队 """
|
||||
pop = que.popleft()
|
||||
print("出队元素 pop =", pop)
|
||||
print("出队后 que =", que)
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = len(que)
|
||||
print("队列长度 size =", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = len(que) == 0
|
||||
print("队列是否为空 =", is_empty)
|
||||
|
||||
@ -1,10 +1,41 @@
|
||||
'''
|
||||
File: stack.py
|
||||
Created Time: 2022-11-25
|
||||
Author: Krahets (krahets@163.com)
|
||||
Created Time: 2022-11-29
|
||||
Author: Peng Chen (pengchzn@gmail.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__":
|
||||
""" 初始化栈 """
|
||||
# Python 没有内置的栈类,可以把 list 当作栈来使用
|
||||
stack = []
|
||||
|
||||
""" 元素入栈 """
|
||||
stack.append(1)
|
||||
stack.append(3)
|
||||
stack.append(2)
|
||||
stack.append(5)
|
||||
stack.append(4)
|
||||
print("栈 stack =", stack)
|
||||
|
||||
""" 访问栈顶元素 """
|
||||
peek = stack[-1]
|
||||
print("栈顶元素 peek =", peek)
|
||||
|
||||
""" 元素出栈 """
|
||||
pop = stack.pop()
|
||||
print("出栈元素 pop =", pop)
|
||||
print("出栈后 stack =", stack)
|
||||
|
||||
""" 获取栈的长度 """
|
||||
size = len(stack)
|
||||
print("栈的长度 size =", size)
|
||||
|
||||
""" 判断是否为空 """
|
||||
is_empty = len(stack) == 0
|
||||
print("栈是否为空 =", is_empty)
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import copy
|
||||
import math
|
||||
import queue
|
||||
import random
|
||||
import functools
|
||||
import collections
|
||||
|
||||
@ -24,7 +24,7 @@ def list_to_tree(arr):
|
||||
[type]: [description]
|
||||
"""
|
||||
if not arr:
|
||||
return
|
||||
return None
|
||||
i = 1
|
||||
root = TreeNode(int(arr[0]))
|
||||
queue = collections.deque()
|
||||
|
||||
@ -4,6 +4,8 @@ Created Time: 2021-12-11
|
||||
Author: Krahets (krahets@163.com)
|
||||
'''
|
||||
|
||||
import copy
|
||||
import queue
|
||||
from .binary_tree import TreeNode, tree_to_list
|
||||
from .linked_list import ListNode, linked_list_to_list
|
||||
|
||||
@ -28,7 +30,6 @@ def print_linked_list(head):
|
||||
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
|
||||
|
||||
101
codes/typescript/chapter_array_and_linkedlist/array.ts
Normal file
101
codes/typescript/chapter_array_and_linkedlist/array.ts
Normal file
@ -0,0 +1,101 @@
|
||||
/*
|
||||
* File: array.ts
|
||||
* Created Time: 2022-12-04
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* 随机返回一个数组元素 */
|
||||
function randomAccess(nums: number[]): number {
|
||||
// 在区间 [0, nums.length) 中随机抽取一个数字
|
||||
const random_index = Math.floor(Math.random() * nums.length)
|
||||
// 获取并返回随机元素
|
||||
const random_num = nums[random_index]
|
||||
return random_num
|
||||
}
|
||||
|
||||
/* 扩展数组长度 */
|
||||
// 请注意,TypeScript 的 Array 是动态数组,可以直接扩展
|
||||
// 为了方便学习,本函数将 Array 看作是长度不可变的数组
|
||||
function extend(nums: number[], enlarge: number): number[] {
|
||||
// 初始化一个扩展长度后的数组
|
||||
const res = new Array(nums.length + enlarge).fill(0)
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
for (let i = 0; i < nums.length; i++){
|
||||
res[i] = nums[i]
|
||||
}
|
||||
// 返回扩展后的新数组
|
||||
return res
|
||||
}
|
||||
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
function insert(nums: number[], num: number, index: number): void {
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for (let i = nums.length - 1; i >= index; i--) {
|
||||
nums[i] = nums[i - 1]
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
nums[index] = num
|
||||
}
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
function remove(nums: number[], index: number): void {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for (let i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1]
|
||||
}
|
||||
}
|
||||
|
||||
/* 遍历数组 */
|
||||
function traverse(nums: number[]): void {
|
||||
let count = 0
|
||||
// 通过索引遍历数组
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++
|
||||
}
|
||||
// 直接遍历数组
|
||||
for(let num of nums){
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
|
||||
/* 在数组中查找指定元素 */
|
||||
function find(nums: number[], target: number): number {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (nums[i] === target) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/* Driver Codes*/
|
||||
/* 初始化数组 */
|
||||
let arr: number[] = new Array(5).fill(0)
|
||||
console.log("数组 arr =", arr)
|
||||
let nums: number[] = [1, 3, 2, 5, 4]
|
||||
console.log("数组 nums =", nums)
|
||||
|
||||
/* 随机访问 */
|
||||
const random_num = randomAccess(nums)
|
||||
console.log("在 nums 中获取随机元素", random_num)
|
||||
|
||||
/* 长度扩展 */
|
||||
nums = extend(nums, 3)
|
||||
console.log("将数组长度扩展至 8 ,得到 nums =", nums)
|
||||
|
||||
/* 插入元素 */
|
||||
insert(nums, 6, 3)
|
||||
console.log("在索引 3 处插入数字 6 ,得到 nums =", nums)
|
||||
|
||||
/* 删除元素 */
|
||||
remove(nums, 2)
|
||||
console.log("删除索引 2 处的元素,得到 nums =", nums)
|
||||
|
||||
/* 遍历数组 */
|
||||
traverse(nums)
|
||||
|
||||
/* 查找元素 */
|
||||
var index: number = find(nums, 3)
|
||||
console.log("在 nums 中查找元素 3 ,得到索引 =", index)
|
||||
|
||||
export { }
|
||||
30
codes/typescript/chapter_stack_and_queue/stack.ts
Normal file
30
codes/typescript/chapter_stack_and_queue/stack.ts
Normal file
@ -0,0 +1,30 @@
|
||||
/**
|
||||
* File: stack.ts
|
||||
* Created Time: 2022-12-04
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* 初始化栈 */
|
||||
// Typescript 没有内置的栈类,可以把 Array 当作栈来使用
|
||||
const stack: number[] = [];
|
||||
|
||||
/* 元素入栈 */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
|
||||
/* 访问栈顶元素 */
|
||||
const peek = stack[stack.length - 1];
|
||||
|
||||
/* 元素出栈 */
|
||||
const pop = stack.pop();
|
||||
|
||||
/* 获取栈的长度 */
|
||||
const size = stack.length;
|
||||
|
||||
/* 判断是否为空 */
|
||||
const is_empty = stack.length === 0;
|
||||
|
||||
export { };
|
||||
@ -24,14 +24,6 @@ comments: true
|
||||
int[] nums = { 1, 3, 2, 5, 4 };
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.javascript"
|
||||
/* 初始化数组 */
|
||||
var arr = new Array(5).fill(0)
|
||||
var nums = [1, 3, 2, 5, 4]
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array.cpp"
|
||||
@ -48,6 +40,40 @@ comments: true
|
||||
nums = [1, 3, 2, 5, 4]
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.js"
|
||||
/* 初始化数组 */
|
||||
var arr = new Array(5).fill(0)
|
||||
var nums = [1, 3, 2, 5, 4]
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="array.ts"
|
||||
/* 初始化数组 */
|
||||
let arr: number[] = new Array(5).fill(0)
|
||||
let nums: number[] = [1, 3, 2, 5, 4]
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array.cs"
|
||||
|
||||
```
|
||||
|
||||
## 数组优点
|
||||
|
||||
**在数组中访问元素非常高效。** 这是因为在数组中,计算元素的内存地址非常容易。给定数组首个元素的地址、和一个元素的索引,利用以下公式可以直接计算得到该元素的内存地址,从而直接访问此元素。
|
||||
@ -77,19 +103,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.javascript"
|
||||
/* 随机返回一个数组元素 */
|
||||
function randomAccess(nums){
|
||||
// 在区间 [0, nums.length) 中随机抽取一个数字
|
||||
const random_index = Math.floor(Math.random() * nums.length)
|
||||
// 获取并返回随机元素
|
||||
random_num = nums[random_index]
|
||||
return random_num
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array.cpp"
|
||||
@ -115,6 +128,50 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
return random_num
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.js"
|
||||
/* 随机返回一个数组元素 */
|
||||
function randomAccess(nums){
|
||||
// 在区间 [0, nums.length) 中随机抽取一个数字
|
||||
const random_index = Math.floor(Math.random() * nums.length)
|
||||
// 获取并返回随机元素
|
||||
random_num = nums[random_index]
|
||||
return random_num
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="array.ts"
|
||||
/* 随机返回一个数组元素 */
|
||||
function randomAccess(nums: number[]): number {
|
||||
// 在区间 [0, nums.length) 中随机抽取一个数字
|
||||
const random_index = Math.floor(Math.random() * nums.length)
|
||||
// 获取并返回随机元素
|
||||
const random_num = nums[random_index]
|
||||
return random_num
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array.cs"
|
||||
|
||||
```
|
||||
|
||||
## 数组缺点
|
||||
|
||||
**数组在初始化后长度不可变。** 由于系统无法保证数组之后的内存空间是可用的,因此数组长度无法扩展。而若希望扩容数组,则需新建一个数组,然后把原数组元素依次拷贝到新数组,在数组很大的情况下,这是非常耗时的。
|
||||
@ -135,22 +192,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.javascript"
|
||||
/* 扩展数组长度 */
|
||||
function extend(nums, enlarge){
|
||||
// 初始化一个扩展长度后的数组
|
||||
let res = new Array(nums.length + enlarge).fill(0)
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
for(let i=0; i<nums.length;i++){
|
||||
res[i] = nums[i]
|
||||
}
|
||||
// 返回扩展后的新数组
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array.cpp"
|
||||
@ -183,6 +224,56 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
return res
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.js"
|
||||
/* 扩展数组长度 */
|
||||
function extend(nums, enlarge){
|
||||
// 初始化一个扩展长度后的数组
|
||||
let res = new Array(nums.length + enlarge).fill(0)
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
for(let i=0; i<nums.length;i++){
|
||||
res[i] = nums[i]
|
||||
}
|
||||
// 返回扩展后的新数组
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="array.ts"
|
||||
/* 扩展数组长度 */
|
||||
function extend(nums: number[], enlarge: number): number[] {
|
||||
// 初始化一个扩展长度后的数组
|
||||
const res = new Array(nums.length + enlarge).fill(0)
|
||||
// 将原数组中的所有元素复制到新数组
|
||||
for (let i = 0; i < nums.length; i++){
|
||||
res[i] = nums[i]
|
||||
}
|
||||
// 返回扩展后的新数组
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array.cs"
|
||||
|
||||
```
|
||||
|
||||
**数组中插入或删除元素效率低下。** 假设我们想要在数组中间某位置插入一个元素,由于数组元素在内存中是 “紧挨着的” ,它们之间没有空间再放任何数据。因此,我们不得不将此索引之后的所有元素都向后移动一位,然后再把元素赋值给该索引。删除元素也是类似,需要把此索引之后的元素都向前移动一位。总体看有以下缺点:
|
||||
|
||||
- **时间复杂度高:** 数组的插入和删除的平均时间复杂度均为 $O(N)$ ,其中 $N$ 为数组长度。
|
||||
@ -215,28 +306,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.javascript"
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
function insert(nums, num, index){
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for (let i = nums.length - 1; i >= index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
function remove(nums, index){
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for (let i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array.cpp"
|
||||
@ -277,6 +346,68 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
nums[i] = nums[i + 1]
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.js"
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
function insert(nums, num, index){
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for (let i = nums.length - 1; i >= index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
function remove(nums, index){
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for (let i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="array.ts"
|
||||
/* 在数组的索引 index 处插入元素 num */
|
||||
function insert(nums: number[], num: number, index: number): void {
|
||||
// 把索引 index 以及之后的所有元素向后移动一位
|
||||
for (let i = nums.length - 1; i >= index; i--) {
|
||||
nums[i] = nums[i - 1]
|
||||
}
|
||||
// 将 num 赋给 index 处元素
|
||||
nums[index] = num
|
||||
}
|
||||
|
||||
/* 删除索引 index 处元素 */
|
||||
function remove(nums: number[], index: number): void {
|
||||
// 把索引 index 之后的所有元素向前移动一位
|
||||
for (let i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array.cs"
|
||||
|
||||
```
|
||||
|
||||
## 数组常用操作
|
||||
|
||||
**数组遍历。** 以下介绍两种常用的遍历方法。
|
||||
@ -298,23 +429,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.javascript"
|
||||
/* 遍历数组 */
|
||||
function traverse(nums){
|
||||
let count = 0
|
||||
// 通过索引遍历数组
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++;
|
||||
}
|
||||
// 直接遍历数组
|
||||
for(let num of nums){
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array.cpp"
|
||||
@ -342,6 +456,58 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
count += 1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.js"
|
||||
/* 遍历数组 */
|
||||
function traverse(nums){
|
||||
let count = 0
|
||||
// 通过索引遍历数组
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++;
|
||||
}
|
||||
// 直接遍历数组
|
||||
for(let num of nums){
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="array.ts"
|
||||
/* 遍历数组 */
|
||||
function traverse(nums: number[]): void {
|
||||
let count = 0
|
||||
// 通过索引遍历数组
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++
|
||||
}
|
||||
// 直接遍历数组
|
||||
for(let num of nums){
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array.cs"
|
||||
|
||||
```
|
||||
|
||||
**数组查找。** 通过遍历数组,查找数组内的指定元素,并输出对应索引。
|
||||
|
||||
=== "Java"
|
||||
@ -357,19 +523,6 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.javascript"
|
||||
/* 在数组中查找指定元素 */
|
||||
function find(nums, target){
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (nums[i] == target)
|
||||
return i;
|
||||
}
|
||||
return -1
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="array.cpp"
|
||||
@ -394,6 +547,51 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
|
||||
return -1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="array.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="array.js"
|
||||
/* 在数组中查找指定元素 */
|
||||
function find(nums, target){
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (nums[i] == target)
|
||||
return i;
|
||||
}
|
||||
return -1
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="array.ts"
|
||||
/* 在数组中查找指定元素 */
|
||||
function find(nums: number[], target: number): number {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (nums[i] === target) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="array.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="array.cs"
|
||||
|
||||
```
|
||||
|
||||
## 数组典型应用
|
||||
|
||||
**随机访问。** 如果我们想要随机抽取一些样本,那么可以用数组存储,并生成一个随机序列,根据索引实现样本的随机抽取。
|
||||
|
||||
@ -48,6 +48,36 @@ comments: true
|
||||
self.next = None # 指向下一结点的指针(引用)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
**尾结点指向什么?** 我们一般将链表的最后一个结点称为「尾结点」,其指向的是「空」,在 Java / C++ / Python 中分别记为 `null` / `nullptr` / `None` 。在不引起歧义下,本书都使用 `null` 来表示空。
|
||||
|
||||
**链表初始化方法。** 建立链表分为两步,第一步是初始化各个结点对象,第二步是构建引用指向关系。完成后,即可以从链表的首个结点(即头结点)出发,访问其余所有的结点。
|
||||
@ -107,6 +137,36 @@ comments: true
|
||||
n3.next = n4
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 链表优点
|
||||
|
||||
**在链表中,插入与删除结点的操作效率高。** 例如,如果想在链表中间的两个结点 `A` , `B` 之间插入一个新结点 `P` ,我们只需要改变两个结点指针即可,时间复杂度为 $O(1)$ ,相比数组的插入操作高效很多。在链表中删除某个结点也很方便,只需要改变一个结点指针即可。
|
||||
@ -176,6 +236,36 @@ comments: true
|
||||
n0.next = n1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 链表缺点
|
||||
|
||||
**链表访问结点效率低。** 上节提到,数组可以在 $O(1)$ 时间下访问任意元素,但链表无法直接访问任意结点。这是因为计算机需要从头结点出发,一个一个地向后遍历到目标结点。例如,倘若想要访问链表索引为 `index` (即第 `index + 1` 个)的结点,那么需要 `index` 次访问操作。
|
||||
@ -220,6 +310,36 @@ comments: true
|
||||
return head
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
**链表的内存占用多。** 链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。
|
||||
|
||||
## 链表常用操作
|
||||
@ -272,6 +392,36 @@ comments: true
|
||||
return -1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 常见链表类型
|
||||
|
||||
**单向链表。** 即上述介绍的普通链表。单向链表的结点有「值」和指向下一结点的「指针(引用)」两项数据。我们将首个结点称为头结点,尾结点指向 `null` 。
|
||||
@ -315,6 +465,36 @@ comments: true
|
||||
self.prev = None # 指向前驱结点的指针(引用)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 常见链表类型 </p>
|
||||
|
||||
@ -35,6 +35,36 @@ comments: true
|
||||
list = [1, 3, 2, 5, 4]
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="list.cs"
|
||||
|
||||
```
|
||||
|
||||
**访问与更新元素。** 列表的底层数据结构是数组,因此可以在 $O(1)$ 时间内访问与更新元素,效率很高。
|
||||
|
||||
=== "Java"
|
||||
@ -67,6 +97,36 @@ comments: true
|
||||
list[1] = 0 # 将索引 1 处的元素更新为 0
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="list.cs"
|
||||
|
||||
```
|
||||
|
||||
**在列表中添加、插入、删除元素。** 相对于数组,列表可以自由地添加与删除元素。在列表尾部添加元素的时间复杂度为 $O(1)$ ,但是插入与删除元素的效率仍与数组一样低,时间复杂度为 $O(N)$ 。
|
||||
|
||||
=== "Java"
|
||||
@ -129,6 +189,36 @@ comments: true
|
||||
list.pop(3) # 删除索引 3 处的元素
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="list.cs"
|
||||
|
||||
```
|
||||
|
||||
**遍历列表。** 与数组一样,列表可以使用索引遍历,也可以使用 `for-each` 直接遍历。
|
||||
|
||||
=== "Java"
|
||||
@ -177,6 +267,36 @@ comments: true
|
||||
count += 1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="list.cs"
|
||||
|
||||
```
|
||||
|
||||
**拼接两个列表。** 再创建一个新列表 `list1` ,我们可以将其中一个列表拼接到另一个的尾部。
|
||||
|
||||
=== "Java"
|
||||
@ -204,6 +324,36 @@ comments: true
|
||||
list += list1 # 将列表 list1 拼接到 list 之后
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="list.cs"
|
||||
|
||||
```
|
||||
|
||||
**排序列表。** 排序也是常用的方法之一,完成列表排序后,我们就可以使用在数组类算法题中经常考察的「二分查找」和「双指针」算法了。
|
||||
|
||||
=== "Java"
|
||||
@ -227,6 +377,36 @@ comments: true
|
||||
list.sort() # 排序后,列表元素从小到大排列
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="list.cs"
|
||||
|
||||
```
|
||||
|
||||
## 列表简易实现 *
|
||||
|
||||
为了帮助加深对列表的理解,我们在此提供一个列表的简易版本的实现。需要关注三个核心点:
|
||||
@ -288,13 +468,13 @@ comments: true
|
||||
}
|
||||
|
||||
/* 中间插入元素 */
|
||||
public void add(int index, int num) {
|
||||
public void insert(int index, int num) {
|
||||
if (index >= size)
|
||||
throw new IndexOutOfBoundsException("索引越界");
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (size == capacity())
|
||||
extendCapacity();
|
||||
// 索引 i 以及之后的元素都向后移动一位
|
||||
// 将索引 index 以及之后的元素都向后移动一位
|
||||
for (int j = size - 1; j >= index; j--) {
|
||||
nums[j + 1] = nums[j];
|
||||
}
|
||||
@ -304,15 +484,18 @@ comments: true
|
||||
}
|
||||
|
||||
/* 删除元素 */
|
||||
public void remove(int index) {
|
||||
public int remove(int index) {
|
||||
if (index >= size)
|
||||
throw new IndexOutOfBoundsException("索引越界");
|
||||
// 索引 i 之后的元素都向前移动一位
|
||||
int num = nums[index];
|
||||
// 将索引 index 之后的元素都向前移动一位
|
||||
for (int j = index; j < size - 1; j++) {
|
||||
nums[j] = nums[j + 1];
|
||||
}
|
||||
// 更新元素数量
|
||||
size--;
|
||||
// 返回被删除元素
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 列表扩容 */
|
||||
@ -356,14 +539,14 @@ comments: true
|
||||
int get(int index) {
|
||||
// 索引如果越界则抛出异常,下同
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
return nums[index];
|
||||
}
|
||||
|
||||
/* 更新元素 */
|
||||
void set(int index, int num) {
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
@ -380,7 +563,7 @@ comments: true
|
||||
/* 中间插入元素 */
|
||||
void insert(int index, int num) {
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (size() == capacity())
|
||||
extendCapacity();
|
||||
@ -394,15 +577,18 @@ comments: true
|
||||
}
|
||||
|
||||
/* 删除元素 */
|
||||
void remove(int index) {
|
||||
int remove(int index) {
|
||||
if (index >= size())
|
||||
throw std::out_of_range ("索引越界");
|
||||
throw out_of_range("索引越界");
|
||||
int num = nums[index];
|
||||
// 索引 i 之后的元素都向前移动一位
|
||||
for (int j = index; j < size() - 1; j++) {
|
||||
nums[j] = nums[j + 1];
|
||||
}
|
||||
// 更新元素数量
|
||||
numsSize--;
|
||||
// 返回被删除元素
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 列表扩容 */
|
||||
@ -419,16 +605,6 @@ comments: true
|
||||
delete[] temp;
|
||||
numsCapacity = newCapacity;
|
||||
}
|
||||
|
||||
/* 将列表转换为 Vector 用于打印 */
|
||||
vector<int> toVector() {
|
||||
// 仅转换有效长度范围内的列表元素
|
||||
vector<int> vec(size());
|
||||
for (int i = 0; i < size(); i++) {
|
||||
vec[i] = nums[i];
|
||||
}
|
||||
return vec;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
@ -439,58 +615,89 @@ comments: true
|
||||
class MyList:
|
||||
""" 构造函数 """
|
||||
def __init__(self):
|
||||
self._capacity = 10 # 列表容量
|
||||
self._nums = [0] * self._capacity # 数组(存储列表元素)
|
||||
self._size = 0 # 列表长度(即当前元素数量)
|
||||
self._extend_ratio = 2 # 每次列表扩容的倍数
|
||||
self.__capacity = 10 # 列表容量
|
||||
self.__nums = [0] * self.__capacity # 数组(存储列表元素)
|
||||
self.__size = 0 # 列表长度(即当前元素数量)
|
||||
self.__extend_ratio = 2 # 每次列表扩容的倍数
|
||||
|
||||
""" 获取列表长度(即当前元素数量) """
|
||||
def size(self):
|
||||
return self._size
|
||||
return self.__size
|
||||
|
||||
""" 获取列表容量 """
|
||||
def capacity(self):
|
||||
return self._capacity
|
||||
return self.__capacity
|
||||
|
||||
""" 访问元素 """
|
||||
def get(self, index):
|
||||
# 索引如果越界则抛出异常,下同
|
||||
assert index < self._size, "索引越界"
|
||||
return self._nums[index]
|
||||
assert index < self.__size, "索引越界"
|
||||
return self.__nums[index]
|
||||
|
||||
""" 更新元素 """
|
||||
def set(self, num, index):
|
||||
assert index < self._size, "索引越界"
|
||||
self._nums[index] = num
|
||||
assert index < self.__size, "索引越界"
|
||||
self.__nums[index] = num
|
||||
|
||||
""" 中间插入元素 """
|
||||
""" 中间插入(尾部添加)元素 """
|
||||
def add(self, num, index=-1):
|
||||
assert index < self._size, "索引越界"
|
||||
assert index < self.__size, "索引越界"
|
||||
# 若不指定索引 index ,则向数组尾部添加元素
|
||||
if index == -1:
|
||||
index = self._size
|
||||
index = self.__size
|
||||
# 元素数量超出容量时,触发扩容机制
|
||||
if self._size == self.capacity():
|
||||
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
|
||||
for j in range(self.__size - 1, index - 1, -1):
|
||||
self.__nums[j + 1] = self.__nums[j]
|
||||
self.__nums[index] = num
|
||||
# 更新元素数量
|
||||
self._size += 1
|
||||
self.__size += 1
|
||||
|
||||
""" 删除元素 """
|
||||
def remove(self, index):
|
||||
assert index < self._size, "索引越界"
|
||||
assert index < self.__size, "索引越界"
|
||||
# 索引 i 之后的元素都向前移动一位
|
||||
for j in range(index, self._size - 1):
|
||||
self._nums[j] = self._nums[j + 1]
|
||||
for j in range(index, self.__size - 1):
|
||||
self.__nums[j] = self.__nums[j + 1]
|
||||
# 更新元素数量
|
||||
self._size -= 1
|
||||
self.__size -= 1
|
||||
|
||||
""" 列表扩容 """
|
||||
def extend_capacity(self):
|
||||
# 新建一个长度为 self._size 的数组,并将原数组拷贝到新数组
|
||||
self._nums = self._nums + [0] * self.capacity() * (self._extend_ratio - 1)
|
||||
# 新建一个长度为 self.__size 的数组,并将原数组拷贝到新数组
|
||||
self.__nums = self.__nums + [0] * self.capacity() * (self.__extend_ratio - 1)
|
||||
# 更新列表容量
|
||||
self._capacity = len(self._nums)
|
||||
self.__capacity = len(self.__nums)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="my_list.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="my_list.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="my_list.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="my_list.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_list.cs"
|
||||
|
||||
```
|
||||
|
||||
@ -16,7 +16,7 @@ comments: true
|
||||
- **时间效率** ,即算法的运行速度的快慢。
|
||||
- **空间效率** ,即算法占用的内存空间大小。
|
||||
|
||||
数据结构与算法追求 “运行地快、内存占用少” ,而如何去评价算法效率则是非常重要的问题。
|
||||
数据结构与算法追求 “运行得快、内存占用少” ,而如何去评价算法效率则是非常重要的问题。
|
||||
|
||||
## 效率评估方法
|
||||
|
||||
|
||||
@ -99,6 +99,36 @@ comments: true
|
||||
return a + b + c # 输出数据
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 推算方法
|
||||
|
||||
空间复杂度的推算方法和时间复杂度总体类似,只是从统计 “计算操作数量” 变为统计 “使用空间大小” 。与时间复杂度不同的是,**我们一般只关注「最差空间复杂度」**。这是因为内存空间是一个硬性要求,我们必须保证在所有输入数据下都有足够的内存空间预留。
|
||||
@ -140,6 +170,36 @@ comments: true
|
||||
nums = [0] * n # O(n)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
**在递归函数中,需要注意统计栈帧空间。** 例如函数 `loop()`,在循环中调用了 $n$ 次 `function()` ,每轮中的 `function()` 都返回并释放了栈帧空间,因此空间复杂度仍为 $O(1)$ 。而递归函数 `recur()` 在运行中会同时存在 $n$ 个未返回的 `recur()` ,从而使用 $O(n)$ 的栈帧空间。
|
||||
|
||||
=== "Java"
|
||||
@ -200,6 +260,36 @@ comments: true
|
||||
return recur(n - 1)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 常见类型
|
||||
|
||||
设输入数据大小为 $n$ ,常见的空间复杂度类型有(从低到高排列)
|
||||
@ -284,6 +374,36 @@ $$
|
||||
function()
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="space_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="space_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="space_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="space_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="space_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
### 线性阶 $O(n)$
|
||||
|
||||
线性阶常见于元素数量与 $n$ 成正比的数组、链表、栈、队列等。
|
||||
@ -341,6 +461,36 @@ $$
|
||||
mapp[i] = str(i)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="space_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="space_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="space_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="space_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="space_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
以下递归函数会同时存在 $n$ 个未返回的 `algorithm()` 函数,使用 $O(n)$ 大小的栈帧空间。
|
||||
|
||||
=== "Java"
|
||||
@ -370,11 +520,41 @@ $$
|
||||
```python title="space_complexity_types.py"
|
||||
""" 线性阶(递归实现) """
|
||||
def linearRecur(n):
|
||||
print("递归 n = ", n)
|
||||
print("递归 n =", n)
|
||||
if n == 1: return
|
||||
linearRecur(n - 1)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="space_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="space_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="space_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="space_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="space_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 递归函数产生的线性阶空间复杂度 </p>
|
||||
@ -428,6 +608,36 @@ $$
|
||||
num_matrix = [[0] * n for _ in range(n)]
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="space_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="space_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="space_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="space_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="space_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
在以下递归函数中,同时存在 $n$ 个未返回的 `algorihtm()` ,并且每个函数中都初始化了一个数组,长度分别为 $n, n-1, n-2, ..., 2, 1$ ,平均长度为 $\frac{n}{2}$ ,因此总体使用 $O(n^2)$ 空间。
|
||||
|
||||
=== "Java"
|
||||
@ -465,6 +675,36 @@ $$
|
||||
return quadratic_recur(n - 1)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="space_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="space_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="space_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="space_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="space_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 递归函数产生的平方阶空间复杂度 </p>
|
||||
@ -511,6 +751,36 @@ $$
|
||||
return root
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="space_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="space_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="space_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="space_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="space_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 满二叉树下的指数阶空间复杂度 </p>
|
||||
|
||||
@ -20,7 +20,7 @@ comments: true
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="leetcode_two_sum.java"
|
||||
```java title="leetcode_two_sum.java"
|
||||
class SolutionBruteForce {
|
||||
public int[] twoSum(int[] nums, int target) {
|
||||
int size = nums.length;
|
||||
@ -85,6 +85,30 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="leetcode_two_sum.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="leetcode_two_sum.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="leetcode_two_sum.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="leetcode_two_sum.cs"
|
||||
|
||||
```
|
||||
|
||||
### 方法二:辅助哈希表
|
||||
|
||||
时间复杂度 $O(N)$ ,空间复杂度 $O(N)$ ,属于「空间换时间」。
|
||||
@ -93,7 +117,7 @@ comments: true
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="leetcode_two_sum.java"
|
||||
```java title="leetcode_two_sum.java"
|
||||
class SolutionHashMap {
|
||||
public int[] twoSum(int[] nums, int target) {
|
||||
int size = nums.length;
|
||||
@ -163,3 +187,27 @@ comments: true
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="leetcode_two_sum.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="leetcode_two_sum.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="leetcode_two_sum.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="leetcode_two_sum.cs"
|
||||
|
||||
```
|
||||
|
||||
@ -15,7 +15,7 @@ comments: true
|
||||
例如以下代码,输入数据大小为 $n$ ,根据以上方法,可以得到算法运行时间为 $6n + 12$ ns 。
|
||||
|
||||
$$
|
||||
1 + 1 + 10 + (1 + 5) \times n = 6n + 12
|
||||
1 + 1 + 10 + (1 + 5) \times n = 6n + 12
|
||||
$$
|
||||
|
||||
=== "Java"
|
||||
@ -61,6 +61,36 @@ $$
|
||||
print(0) # 5 ns
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
但实际上, **统计算法的运行时间既不合理也不现实。** 首先,我们不希望预估时间和运行平台绑定,毕竟算法需要跑在各式各样的平台之上。其次,我们很难获知每一种操作的运行时间,这为预估过程带来了极大的难度。
|
||||
|
||||
## 统计时间增长趋势
|
||||
@ -131,6 +161,36 @@ $$
|
||||
print(0)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 算法 A, B, C 的时间增长趋势 </p>
|
||||
@ -192,6 +252,36 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
$T(n)$ 是个一次函数,说明时间增长趋势是线性的,因此易得时间复杂度是线性阶。
|
||||
|
||||
我们将线性阶的时间复杂度记为 $O(n)$ ,这个数学符号被称为「大 $O$ 记号 Big-$O$ Notation」,代表函数 $T(n)$ 的「渐进上界 asymptotic upper bound」。
|
||||
@ -296,6 +386,36 @@ $$
|
||||
print(0)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
### 2. 判断渐进上界
|
||||
|
||||
**时间复杂度由多项式 $T(n)$ 中最高阶的项来决定**。这是因为在 $n$ 趋于无穷大时,最高阶的项将处于主导作用,其它项的影响都可以被忽略。
|
||||
@ -341,7 +461,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 常数阶 */
|
||||
int constant(int n) {
|
||||
int count = 0;
|
||||
@ -377,13 +497,43 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
### 线性阶 $O(n)$
|
||||
|
||||
线性阶的操作数量相对输入数据大小成线性级别增长。线性阶常出现于单层循环。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 线性阶 */
|
||||
int linear(int n) {
|
||||
int count = 0;
|
||||
@ -416,6 +566,36 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
「遍历数组」和「遍历链表」等操作,时间复杂度都为 $O(n)$ ,其中 $n$ 为数组或链表的长度。
|
||||
|
||||
!!! tip
|
||||
@ -424,7 +604,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 线性阶(遍历数组) */
|
||||
int arrayTraversal(int[] nums) {
|
||||
int count = 0;
|
||||
@ -462,13 +642,43 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
### 平方阶 $O(n^2)$
|
||||
|
||||
平方阶的操作数量相对输入数据大小成平方级别增长。平方阶常出现于嵌套循环,外层循环和内层循环都为 $O(n)$ ,总体为 $O(n^2)$ 。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 平方阶 */
|
||||
int quadratic(int n) {
|
||||
int count = 0;
|
||||
@ -511,6 +721,36 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 常数阶、线性阶、平方阶的时间复杂度 </p>
|
||||
@ -523,7 +763,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 平方阶(冒泡排序) */
|
||||
int bubbleSort(int[] nums) {
|
||||
int count = 0; // 计数器
|
||||
@ -586,17 +826,47 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
### 指数阶 $O(2^n)$
|
||||
|
||||
!!! note
|
||||
|
||||
生物学科中的 “细胞分裂” 即是指数阶增长:初始状态为 $1$ 个细胞,分裂一轮后为 $2$ 个,分裂两轮后为 $4$ 个,……,分裂 $n$ 轮后有 $2^n$ 个细胞。
|
||||
|
||||
指数阶增长地非常快,在实际应用中一般是不能被接受的。若一个问题使用「暴力枚举」求解的时间复杂度是 $O(2^n)$ ,那么一般都需要使用「动态规划」或「贪心算法」等算法来求解。
|
||||
指数阶增长得非常快,在实际应用中一般是不能被接受的。若一个问题使用「暴力枚举」求解的时间复杂度是 $O(2^n)$ ,那么一般都需要使用「动态规划」或「贪心算法」等算法来求解。
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 指数阶(循环实现) */
|
||||
int exponential(int n) {
|
||||
int count = 0, base = 1;
|
||||
@ -645,6 +915,36 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 指数阶的时间复杂度 </p>
|
||||
@ -653,7 +953,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 指数阶(递归实现) */
|
||||
int expRecur(int n) {
|
||||
if (n == 1) return 1;
|
||||
@ -680,6 +980,36 @@ $$
|
||||
return exp_recur(n - 1) + exp_recur(n - 1) + 1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
### 对数阶 $O(\log n)$
|
||||
|
||||
对数阶与指数阶正好相反,后者反映 “每轮增加到两倍的情况” ,而前者反映 “每轮缩减到一半的情况” 。对数阶仅次于常数阶,时间增长的很慢,是理想的时间复杂度。
|
||||
@ -690,7 +1020,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 对数阶(循环实现) */
|
||||
int logarithmic(float n) {
|
||||
int count = 0;
|
||||
@ -728,6 +1058,36 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 对数阶的时间复杂度 </p>
|
||||
@ -736,7 +1096,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 对数阶(递归实现) */
|
||||
int logRecur(float n) {
|
||||
if (n <= 1) return 0;
|
||||
@ -763,6 +1123,36 @@ $$
|
||||
return log_recur(n / 2) + 1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||
### 线性对数阶 $O(n \log n)$
|
||||
|
||||
线性对数阶常出现于嵌套循环中,两层循环的时间复杂度分别为 $O(\log n)$ 和 $O(n)$ 。
|
||||
@ -771,7 +1161,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 线性对数阶 */
|
||||
int linearLogRecur(float n) {
|
||||
if (n <= 1) return 1;
|
||||
@ -812,6 +1202,36 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 线性对数阶的时间复杂度 </p>
|
||||
@ -828,7 +1248,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="time_complexity_types.java"
|
||||
```java title="time_complexity_types.java"
|
||||
/* 阶乘阶(递归实现) */
|
||||
int factorialRecur(int n) {
|
||||
if (n == 0) return 1;
|
||||
@ -869,6 +1289,36 @@ $$
|
||||
return count
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="time_complexity_types.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="time_complexity_types.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="time_complexity_types.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="time_complexity_types.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="time_complexity_types.cs"
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> Fig. 阶乘阶的时间复杂度 </p>
|
||||
@ -884,7 +1334,7 @@ $$
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java title="" title="worst_best_time_complexity.java"
|
||||
```java title="worst_best_time_complexity.java"
|
||||
public class worst_best_time_complexity {
|
||||
/* 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱 */
|
||||
static int[] randomNumbers(int n) {
|
||||
@ -994,6 +1444,36 @@ $$
|
||||
print("数字 1 的索引为", index)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="worst_best_time_complexity.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="worst_best_time_complexity.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="worst_best_time_complexity.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="worst_best_time_complexity.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="worst_best_time_complexity.cs"
|
||||
|
||||
```
|
||||
|
||||
!!! tip
|
||||
|
||||
我们在实际应用中很少使用「最佳时间复杂度」,因为往往只有很小概率下才能达到,会带来一定的误导性。反之,「最差时间复杂度」最为实用,因为它给出了一个 “效率安全值” ,让我们可以放心地使用算法。
|
||||
|
||||
@ -46,7 +46,7 @@ comments: true
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java
|
||||
```java title=""
|
||||
/* 使用多种「基本数据类型」来初始化「数组」 */
|
||||
int[] numbers = new int[5];
|
||||
float[] decimals = new float[5];
|
||||
@ -66,6 +66,36 @@ comments: true
|
||||
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 计算机内存
|
||||
|
||||
在计算机中,内存和硬盘是两种主要的存储硬件设备。「硬盘」主要用于长期存储数据,容量较大(通常可达到 TB 级别)、速度较慢。「内存」用于运行程序时暂存数据,速度更快,但容量较小(通常为 GB 级别)。
|
||||
|
||||
17
docs/chapter_hashing/hash_collision.md
Normal file
17
docs/chapter_hashing/hash_collision.md
Normal file
@ -0,0 +1,17 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 哈希冲突处理
|
||||
|
||||
|
||||
|
||||
## 链地址法
|
||||
|
||||
|
||||
|
||||
## 开放定址法
|
||||
|
||||
|
||||
|
||||
## 再哈希法
|
||||
153
docs/chapter_hashing/hash_map.md
Normal file
153
docs/chapter_hashing/hash_map.md
Normal file
@ -0,0 +1,153 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 哈希表
|
||||
|
||||
哈希表通过建立「键 Key」和「值 Value」之间的映射,实现高效的元素查找。具体地,查询操作(给定一个 Key 查询得到 Value)的时间复杂度为 $O(1)$ 。
|
||||
|
||||
(图)
|
||||
|
||||
## 哈希表常用操作
|
||||
|
||||
哈希表的基本操作包括 **初始化、查询操作、添加与删除键值对**。
|
||||
|
||||
```java title="hash_map.java"
|
||||
/* 初始化哈希表 */
|
||||
Map<Integer, String> map = new HashMap<>();
|
||||
|
||||
/* 添加操作 */
|
||||
// 在哈希表中添加键值对 (key, value)
|
||||
map.put(10001, "小哈");
|
||||
map.put(10002, "小啰");
|
||||
map.put(10003, "小算");
|
||||
map.put(10004, "小法");
|
||||
map.put(10005, "小哇");
|
||||
|
||||
/* 查询操作 */
|
||||
// 向哈希表输入键 key ,得到值 value
|
||||
String name = map.get(10002);
|
||||
|
||||
/* 删除操作 */
|
||||
// 在哈希表中删除键值对 (key, value)
|
||||
map.remove(10005);
|
||||
```
|
||||
|
||||
遍历哈希表有三种方式,即 **遍历键值对、遍历键、遍历值**。
|
||||
|
||||
```java
|
||||
/* 遍历哈希表 */
|
||||
// 遍历键值对 Key->Value
|
||||
for (Map.Entry <Integer, String> kv: map.entrySet()) {
|
||||
System.out.println(kv.getKey() + " -> " + kv.getValue());
|
||||
}
|
||||
// 单独遍历键 Key
|
||||
for (int key: map.keySet()) {
|
||||
System.out.println(key);
|
||||
}
|
||||
// 单独遍历值 Value
|
||||
for (String val: map.values()) {
|
||||
System.out.println(val);
|
||||
}
|
||||
```
|
||||
|
||||
## 哈希表优势
|
||||
|
||||
给定一个包含 $n$ 个学生的数据库,每个学生有 "姓名 `name` ” 和 “学号 `id` ” 两项数据,希望实现一个查询功能,即 **输入一个学号,返回对应的姓名**,那么可以使用哪些数据结构来存储呢?
|
||||
|
||||
- **无序数组:** 每个元素为 `[学号, 姓名]` ;
|
||||
- **有序数组:** 将 `1.` 中的数组按照学号从小到大排序;
|
||||
- **链表:** 每个结点的值为 `[学号, 姓名]` ;
|
||||
- **二叉搜索树:** 每个结点的值为 `[学号, 姓名]` ,根据学号大小来构建树;
|
||||
- **哈希表:** 以学号为 Key 、姓名为 Value 。
|
||||
|
||||
使用上述方法,各项操作的时间复杂度如下表所示(在此不做赘述,详解可见 [二叉搜索树章节](https://www.hello-algo.com/chapter_tree/binary_search_tree/#_6)),**哈希表全面胜出!**
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| | 无序数组 | 有序数组 | 链表 | 二叉搜索树 | 哈希表 |
|
||||
| ------------ | -------- | ----------- | ------ | ----------- | ------ |
|
||||
| 查找指定元素 | $O(n)$ | $O(\log n)$ | $O(n)$ | $O(\log n)$ | $O(1)$ |
|
||||
| 插入元素 | $O(1)$ | $O(n)$ | $O(1)$ | $O(\log n)$ | $O(1)$ |
|
||||
| 删除元素 | $O(n)$ | $O(n)$ | $O(n)$ | $O(\log n)$ | $O(1)$ |
|
||||
|
||||
</div>
|
||||
|
||||
## 哈希函数
|
||||
|
||||
哈希表中存储元素的数据结构被称为「桶 Bucket」,底层实现可能是数组、链表、二叉树(红黑树),或是它们的组合。
|
||||
|
||||
最简单地,**我们可以仅用一个「数组」来实现哈希表**。首先,将所有 Value 放入数组中,那么每个 Value 在数组中都有唯一的「索引」。显然,访问 Value 需要给定索引,而为了 **建立 Key 和索引之间的映射关系**,我们需要使用「哈希函数 Hash Function」。
|
||||
|
||||
设数组为 `bucket` ,哈希函数为 `f(x)` ,输入键为 `key` 。那么获取 Value 的步骤为:
|
||||
|
||||
1. 通过哈希函数计算出索引,即 `index = f(key)` ;
|
||||
2. 通过索引在数组中获取值,即 `value = bucket[index]` ;
|
||||
|
||||
以上述学生数据 `Key 学号 -> Value 姓名` 为例,我们可以将「哈希函数」设计为
|
||||
|
||||
$$
|
||||
f(x) = x \% 10000
|
||||
$$
|
||||
|
||||
(图)
|
||||
|
||||
```java title="array_hash_map.java"
|
||||
/* 键值对 int->String */
|
||||
class Entry {
|
||||
public int key; // 键
|
||||
public String val; // 值
|
||||
public Entry(int key, String val) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* 基于数组简易实现的哈希表 */
|
||||
class ArrayHashMap {
|
||||
private List<Entry> bucket;
|
||||
public ArrayHashMap() {
|
||||
// 初始化一个长度为 10 的桶(数组)
|
||||
bucket = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
bucket.add(null);
|
||||
}
|
||||
}
|
||||
|
||||
/* 哈希函数 */
|
||||
private int hashFunc(int key) {
|
||||
int index = key % 10000;
|
||||
return index;
|
||||
}
|
||||
|
||||
/* 查询操作 */
|
||||
public String get(int key) {
|
||||
int index = hashFunc(key);
|
||||
Entry pair = bucket.get(index);
|
||||
if (pair == null) return null;
|
||||
return pair.val;
|
||||
}
|
||||
|
||||
/* 添加操作 */
|
||||
public void put(int key, String val) {
|
||||
Entry pair = new Entry(key, val);
|
||||
int index = hashFunc(key);
|
||||
bucket.set(index, pair);
|
||||
}
|
||||
|
||||
/* 删除操作 */
|
||||
public void remove(int key) {
|
||||
int index = hashFunc(key);
|
||||
// 置为空字符,代表删除
|
||||
bucket.set(index, null);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 哈希冲突
|
||||
|
||||
细心的同学可能会发现,哈希函数 $f(x) = x \% 10000$ 会在某些情况下失效。例如,当输入的 Key 为 10001, 20001, 30001, ... 时,哈希函数的计算结果都是 1 ,指向同一个 Value ,表明不同学号指向了同一个人,这明显是不对的。
|
||||
|
||||
上述现象被称为「哈希冲突 Hash Collision」,其会严重影响查询的正确性,我们将如何避免哈希冲突的问题留在下章讨论。
|
||||
|
||||
(图)
|
||||
5
docs/chapter_hashing/summary.md
Normal file
5
docs/chapter_hashing/summary.md
Normal file
@ -0,0 +1,5 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 小结
|
||||
@ -111,8 +111,6 @@ comments: true
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢本开源书的每一位撰稿人,是他们的无私奉献让这本书变得更好,他们的 GitHub ID(按首次提交时间排序)为:krahets, Reanon.
|
||||
|
||||
本书的成书过程中,我获得了许多人的帮助,包括但不限于:
|
||||
|
||||
- 感谢我的女朋友泡泡担任本书的首位读者,从算法小白的视角为本书的写作提出了许多建议,使这本书更加适合算法初学者来阅读。
|
||||
|
||||
@ -10,11 +10,6 @@ comments: true
|
||||
|
||||
本书推荐使用开源轻量的 VSCode 作为本地 IDE ,下载并安装 [VSCode](https://code.visualstudio.com/) 。
|
||||
|
||||
## Python 环境
|
||||
|
||||
1. 下载并安装 [Miniconda3](https://docs.conda.io/en/latest/miniconda.html) ,获取 Python 运行环境。
|
||||
2. 在 VSCode 的插件市场中搜索 `python` ,安装 Python Extension Pack 。
|
||||
|
||||
## Java 环境
|
||||
|
||||
1. 下载并安装 [OpenJDK](https://jdk.java.net/18/) ,获取 Java 运行环境。
|
||||
@ -24,3 +19,19 @@ comments: true
|
||||
|
||||
1. Windows 系统需要安装 [MinGW](https://www.mingw-w64.org/downloads/) ,MacOS 自带 Clang 无需安装。
|
||||
2. 在 VSCode 的插件市场中搜索 `c++` ,安装 C/C++ Extension Pack 。
|
||||
|
||||
## Python 环境
|
||||
|
||||
1. 下载并安装 [Miniconda3](https://docs.conda.io/en/latest/miniconda.html) ,获取 Python 运行环境。
|
||||
2. 在 VSCode 的插件市场中搜索 `python` ,安装 Python Extension Pack 。
|
||||
|
||||
## Go 环境
|
||||
|
||||
1. 下载并安装 [go](https://go.dev/dl/) ,获取 Go 运行环境。
|
||||
2. 在 VSCode 的插件市场中搜索 `go` ,安装 Go 。
|
||||
3. 快捷键 `Ctrl + Shift + P` 呼出命令栏,输入 go ,选择 `Go: Install/Update Tools` ,全部勾选并安装即可。
|
||||
|
||||
## JavaScript 环境
|
||||
|
||||
1. 下载并安装 [node.js](https://nodejs.org/en/) ,获取 JavaScript 运行环境。
|
||||
2. 在 VSCode 的插件市场中搜索 `javascript` ,安装 JavaScript (ES6) code snippets 。
|
||||
|
||||
@ -102,6 +102,54 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search.py"
|
||||
""" 二分查找(双闭区间) """
|
||||
def binary_search(nums, target):
|
||||
# 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
|
||||
i, j = 0, len(nums) - 1
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # 计算中点索引 m
|
||||
if nums[m] < target: # 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1
|
||||
elif nums[m] > target: # 此情况说明 target 在区间 [i, m-1] 中
|
||||
j = m - 1
|
||||
else:
|
||||
return m # 找到目标元素,返回其索引
|
||||
return -1 # 未找到目标元素,返回 -1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="binary_search.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="binary_search.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search.cs"
|
||||
|
||||
```
|
||||
|
||||
### “左闭右开” 实现
|
||||
|
||||
当然,我们也可以使用 “左闭右开” 的表示方法,写出相同功能的二分查找代码。
|
||||
@ -150,6 +198,55 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="binary_search.py"
|
||||
""" 二分查找(左闭右开) """
|
||||
def binary_search1(nums, target):
|
||||
# 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
i, j = 0, len(nums)
|
||||
# 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while i < j:
|
||||
m = (i + j) // 2 # 计算中点索引 m
|
||||
if nums[m] < target: # 此情况说明 target 在区间 [m+1, j) 中
|
||||
i = m + 1
|
||||
elif nums[m] > target: # 此情况说明 target 在区间 [i, m) 中
|
||||
j = m
|
||||
else: # 找到目标元素,返回其索引
|
||||
return m
|
||||
return -1 # 未找到目标元素,返回 -1
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="binary_search.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="binary_search.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="binary_search.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="binary_search.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search.cs"
|
||||
|
||||
```
|
||||
|
||||
### 两种表示对比
|
||||
|
||||
对比下来,两种表示的代码写法有以下不同点:
|
||||
@ -169,12 +266,60 @@ $$
|
||||
|
||||
当数组长度很大时,加法 $i + j$ 的结果有可能会超出 `int` 类型的取值范围。在此情况下,我们需要换一种计算中点的写法。
|
||||
|
||||
```java
|
||||
// (i + j) 有可能超出 int 的取值范围
|
||||
int m = (i + j) / 2;
|
||||
// 更换为此写法则不会越界
|
||||
int m = i + (j - i) / 2;
|
||||
```
|
||||
=== "Java"
|
||||
|
||||
```java title=""
|
||||
// (i + j) 有可能超出 int 的取值范围
|
||||
int m = (i + j) / 2;
|
||||
// 更换为此写法则不会越界
|
||||
int m = i + (j - i) / 2;
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title=""
|
||||
// (i + j) 有可能超出 int 的取值范围
|
||||
int m = (i + j) / 2;
|
||||
// 更换为此写法则不会越界
|
||||
int m = i + (j - i) / 2;
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```py title=""
|
||||
# Python 中的数字理论上可以无限大(取决于内存大小)
|
||||
# 因此无需考虑大数越界问题
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title=""
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title=""
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title=""
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title=""
|
||||
|
||||
```
|
||||
|
||||
## 复杂度分析
|
||||
|
||||
@ -191,6 +336,6 @@ int m = i + (j - i) / 2;
|
||||
|
||||
但并不意味着所有情况下都应使用二分查找,这是因为:
|
||||
|
||||
- **二分查找仅适用于有序数据。** 如果输入数据是乱序的,为了使用二分查找而专门执行数据排序,那么是得不偿失的,因为排序算法的时间复杂度一般为 $O(n \log n)$ ,比线性查找和二分查找都更差。再例如,对于频繁插入元素的场景,为了保持数组的有序性,需要将元素插入到特定位置,时间复杂度为 $O(n)$ ,也是非常昂贵的。
|
||||
- **二分查找仅适用于有序数据。** 如果输入数据是无序的,为了使用二分查找而专门执行数据排序,那么是得不偿失的,因为排序算法的时间复杂度一般为 $O(n \log n)$ ,比线性查找和二分查找都更差。再例如,对于频繁插入元素的场景,为了保持数组的有序性,需要将元素插入到特定位置,时间复杂度为 $O(n)$ ,也是非常昂贵的。
|
||||
- **二分查找仅适用于数组。** 由于在二分查找中,访问索引是 ”非连续“ 的,因此链表或者基于链表实现的数据结构都无法使用。
|
||||
- **在小数据量下,线性查找的性能更好。** 在线性查找中,每轮只需要 1 次判断操作;而在二分查找中,需要 1 次加法、1 次除法、1 ~ 3 次判断操作、1 次加法(减法),共 4 ~ 6 个单元操作;因此,在数据量 $n$ 较小时,线性查找反而比二分查找更快。
|
||||
|
||||
@ -40,6 +40,46 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="hashing_search.py"
|
||||
""" 哈希查找(数组) """
|
||||
def hashing_search(mapp, target):
|
||||
# 哈希表的 key: 目标元素,value: 索引
|
||||
# 若哈希表中无此 key ,返回 -1
|
||||
return mapp.get(target, -1)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="hashing_search.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="hashing_search.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="hashing_search.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="hashing_search.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="hashing_search.cs"
|
||||
|
||||
```
|
||||
|
||||
再比如,如果我们想要给定一个目标结点值 `target` ,获取对应的链表结点对象,那么也可以使用哈希查找实现。
|
||||
|
||||

|
||||
@ -68,6 +108,46 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python title="hashing_search.py"
|
||||
""" 哈希查找(链表) """
|
||||
def hashing_search1(mapp, target):
|
||||
# 哈希表的 key: 目标元素,value: 结点对象
|
||||
# 若哈希表中无此 key ,返回 -1
|
||||
return mapp.get(target, -1)
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
|
||||
```go title="hashing_search.go"
|
||||
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="hashing_search.js"
|
||||
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="hashing_search.ts"
|
||||
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="hashing_search.c"
|
||||
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="hashing_search.cs"
|
||||
|
||||
```
|
||||
|
||||
## 复杂度分析
|
||||
|
||||
**时间复杂度:** $O(1)$ ,哈希表的查找操作使用 $O(1)$ 时间。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user