Merge branch 'master' of github.com:krahets/hello-algo
This commit is contained in:
commit
460d42ae3d
@ -23,25 +23,28 @@ struct TreeNode {
|
||||
* @param list
|
||||
* @return TreeNode*
|
||||
*/
|
||||
TreeNode* vecToTree(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* vecToTree(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)
|
||||
|
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)
|
@ -1,10 +1,110 @@
|
||||
'''
|
||||
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 = [None] * 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 put(self, val):
|
||||
if self.size() == self.capacity():
|
||||
print("队列已满")
|
||||
return False
|
||||
# 尾结点后添加 num
|
||||
self.__nums[self.__rear] = val
|
||||
# 尾指针向后移动一位,越过尾部后返回到数组头部
|
||||
self.__rear = (self.__rear + 1) % self.capacity()
|
||||
|
||||
""" 出队 """
|
||||
def get(self):
|
||||
# 删除头结点
|
||||
if self.is_empty():
|
||||
print("队列为空")
|
||||
return False
|
||||
num = self.__nums[self.__front]
|
||||
# 队头指针向后移动,越过尾部后返回到数组头部
|
||||
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_index(self, index):
|
||||
if index >= self.size():
|
||||
print("索引越界")
|
||||
return False
|
||||
return self.__nums[(self.__front + index) % self.capacity()]
|
||||
|
||||
""" 返回列表用于打印 """
|
||||
def to_list(self):
|
||||
res = [None] * self.size()
|
||||
j = self.__front
|
||||
for i in range(self.size()):
|
||||
res[i] = self.__nums[(j % self.capacity())]
|
||||
j += 1
|
||||
return res
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
queue = ArrayQueue(10)
|
||||
|
||||
""" 元素入队 """
|
||||
queue.put(1)
|
||||
queue.put(3)
|
||||
queue.put(2)
|
||||
queue.put(5)
|
||||
queue.put(4)
|
||||
print("队列 queue = ", queue.to_list())
|
||||
|
||||
""" 访问队首元素 """
|
||||
peek = queue.peek()
|
||||
print("队首元素 peek = ", peek)
|
||||
|
||||
""" 访问索引 index 处元素 """
|
||||
num = queue.get_index(3)
|
||||
print("队列索引 3 处的元素为 num =", num)
|
||||
|
||||
""" 元素出队 """
|
||||
get = queue.get()
|
||||
print("出队元素 get = ", get)
|
||||
print("出队后 queue = ", queue.to_list())
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = queue.size()
|
||||
print("队列长度 size = ", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = queue.is_empty()
|
||||
print("队列是否为空 = ", is_empty)
|
||||
|
@ -60,8 +60,8 @@ if __name__ == "__main__":
|
||||
print("栈顶元素 peek =", peek)
|
||||
|
||||
""" 访问索引 index 处元素 """
|
||||
num = stack.get(3);
|
||||
print("栈索引 3 处的元素为 num =", num);
|
||||
num = stack.get(3)
|
||||
print("栈索引 3 处的元素为 num =", num)
|
||||
|
||||
""" 元素出栈 """
|
||||
pop = stack.pop()
|
||||
|
@ -1,10 +1,47 @@
|
||||
'''
|
||||
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
|
||||
|
||||
if __name__ == "__main__":
|
||||
""" 初始化双向队列 """
|
||||
duque = deque()
|
||||
|
||||
""" 元素入队 """
|
||||
duque.append(2) # 添加至队尾
|
||||
duque.append(5)
|
||||
duque.append(4)
|
||||
duque.appendleft(3) # 添加至队首
|
||||
duque.appendleft(1)
|
||||
print("双向队列 duque = ", duque)
|
||||
|
||||
""" 访问队首元素 """
|
||||
peekFirst = duque[0] # 队首元素
|
||||
print("队首元素 peekFirst = ", peekFirst)
|
||||
peekLast = duque[-1] # 队尾元素
|
||||
print("队尾元素 peekLast = ", peekLast)
|
||||
|
||||
""" 元素出队 """
|
||||
popFirst = duque.pop() # 队首元素出队
|
||||
print("队首出队元素 popFirst= ", popFirst)
|
||||
print("队首出队后 duque = ", duque)
|
||||
popLast = duque.popleft() # 队尾元素出队
|
||||
print("队尾出队元素 popLast= ", popLast)
|
||||
print("队尾出队后 duque = ", duque)
|
||||
|
||||
""" 获取双向队列的长度 """
|
||||
size = len(duque)
|
||||
print("双向队列长度 size = ", size)
|
||||
|
||||
""" 判断双向队列是否为空 """
|
||||
is_empty = len(duque) == 0
|
||||
print("双向队列是否为空 = ", is_empty)
|
||||
|
@ -1,10 +1,94 @@
|
||||
'''
|
||||
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 = 0 # 头结点 front
|
||||
self.__rear = 0 # 尾结点 rear
|
||||
self.__size = 0
|
||||
|
||||
""" 获取队列的长度 """
|
||||
def size(self):
|
||||
return self.__size
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
def is_empty(self):
|
||||
return not self.__front
|
||||
|
||||
""" 入队 """
|
||||
def put(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 get(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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
queue = LinkedListQueue()
|
||||
|
||||
""" 元素入队 """
|
||||
queue.put(1)
|
||||
queue.put(3)
|
||||
queue.put(2)
|
||||
queue.put(5)
|
||||
queue.put(4)
|
||||
print("队列 queue = ", queue.to_list())
|
||||
|
||||
""" 访问队首元素 """
|
||||
peek = queue.peek()
|
||||
print("队首元素 front = ", peek)
|
||||
|
||||
""" 元素出队 """
|
||||
get = queue.get()
|
||||
print("出队元素 get = ", get)
|
||||
print("出队后 queue = ", queue.to_list())
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = queue.size()
|
||||
print("队列长度 size = ", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = queue.is_empty()
|
||||
print("队列是否为空 = ", is_empty)
|
||||
|
@ -1,10 +1,42 @@
|
||||
'''
|
||||
File: queue.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 *
|
||||
|
||||
import queue
|
||||
|
||||
if __name__ == "__main__":
|
||||
""" 初始化队列 """
|
||||
queue = queue.Queue()
|
||||
|
||||
""" 元素入队 """
|
||||
queue.put(1)
|
||||
queue.put(3)
|
||||
queue.put(2)
|
||||
queue.put(5)
|
||||
queue.put(4)
|
||||
print("队列 queue = ", queue.queue)
|
||||
|
||||
""" 访问队首元素 """
|
||||
peek = queue.queue[0]
|
||||
print("队首元素 peek = ", peek)
|
||||
|
||||
""" 元素出队 """
|
||||
get = queue.get()
|
||||
print("出队元素 get = ", get)
|
||||
print("出队后 queue = ", queue.queue)
|
||||
|
||||
""" 获取队列的长度 """
|
||||
size = queue.qsize()
|
||||
print("队列长度 size = ", size)
|
||||
|
||||
""" 判断队列是否为空 """
|
||||
is_empty = queue.empty()
|
||||
print("队列是否为空 = ", is_empty)
|
||||
|
@ -73,6 +73,27 @@ comments: true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="bubble_sort.js"
|
||||
/* 冒泡排序 */
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="bubble_sort.cpp"
|
||||
@ -149,6 +170,29 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="bubble_sort.js"
|
||||
/* 冒泡排序(标志优化)*/
|
||||
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; // 此轮冒泡未交换任何元素,直接跳出
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="bubble_sort.cpp"
|
||||
|
@ -42,6 +42,24 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="insertion_sort.js"
|
||||
/* 插入排序 */
|
||||
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 赋值到正确位置
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="insertion_sort.cpp"
|
||||
|
@ -103,6 +103,51 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="merge_sort.js"
|
||||
/**
|
||||
* 合并左子数组和右子数组
|
||||
* 左子数组区间 [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);
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="merge_sort.cpp"
|
||||
|
@ -61,6 +61,35 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
``` js title="quick_sort.js"
|
||||
/* 元素交换 */
|
||||
function swap(nums, i, j) {
|
||||
let tmp = nums[i]
|
||||
nums[i] = nums[j]
|
||||
nums[j] = tmp
|
||||
}
|
||||
|
||||
/* 哨兵划分 */
|
||||
function 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 // 从左向右找首个大于基准数的元素
|
||||
}
|
||||
// 元素交换
|
||||
swap(nums, i, j) // 交换这两个元素
|
||||
}
|
||||
swap(nums, i, left) // 将基准数交换至两子数组的分界线
|
||||
return i // 返回基准数的索引
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="quick_sort.cpp"
|
||||
@ -138,6 +167,21 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="quick_sort.js"
|
||||
/* 快速排序 */
|
||||
function quickSort(nums, left, right){
|
||||
// 子数组长度为 1 时终止递归
|
||||
if(left >= right) return
|
||||
// 哨兵划分
|
||||
const pivot = partition(nums, left, right)
|
||||
// 递归左子数组、右子数组
|
||||
quick_sort(nums, left, pivot - 1)
|
||||
quick_sort(nums, pivot + 1, right)
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="quick_sort.cpp"
|
||||
@ -225,6 +269,32 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="quick_sort.js"
|
||||
/* 选取三个元素的中位数 */
|
||||
function 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;
|
||||
}
|
||||
|
||||
/* 哨兵划分(三数取中值) */
|
||||
function partition(nums, left, right) {
|
||||
// 选取三个候选元素的中位数
|
||||
let med = medianThree(nums, left, Math.floor((left + right) / 2), right);
|
||||
// 将中位数交换至数组最左端
|
||||
swap(nums, left, med);
|
||||
// 以 nums[left] 作为基准数
|
||||
// 下同省略...
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="quick_sort.cpp"
|
||||
@ -301,6 +371,27 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
||||
```js title="quick_sort.js"
|
||||
/* 快速排序(尾递归优化) */
|
||||
quickSort(nums, left, right) {
|
||||
// 子数组长度为 1 时终止
|
||||
while (left < right) {
|
||||
// 哨兵划分操作
|
||||
let pivot = partition(nums, left, right);
|
||||
// 对两个子数组中较短的那个执行快排
|
||||
if (pivot - left < right - pivot) {
|
||||
quickSort(nums, left, pivot - 1); // 递归排序左子数组
|
||||
left = pivot + 1; // 剩余待排序区间为 [pivot + 1, right]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // 递归排序右子数组
|
||||
right = pivot - 1; // 剩余待排序区间为 [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="quick_sort.cpp"
|
||||
|
Loading…
Reference in New Issue
Block a user