mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-14 01:38:18 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -4,61 +4,61 @@
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/* Random access to element */
|
||||
/* Access an element at a random index */
|
||||
function randomAccess(nums) {
|
||||
// Randomly select a number in the interval [0, nums.length)
|
||||
// Choose a random index in the interval [0, nums.length)
|
||||
const random_index = Math.floor(Math.random() * nums.length);
|
||||
// Retrieve and return the random element
|
||||
// Get and return the randomly selected element
|
||||
const random_num = nums[random_index];
|
||||
return random_num;
|
||||
}
|
||||
|
||||
/* Extend array length */
|
||||
// Note: JavaScript's Array is dynamic array, can be directly expanded
|
||||
// For learning purposes, this function treats Array as fixed-length array
|
||||
/* Extend the array length */
|
||||
// JavaScript Array is a dynamic array and can be extended directly
|
||||
// For learning purposes, this function treats Array as a fixed-length array
|
||||
function extend(nums, enlarge) {
|
||||
// Initialize an array with extended length
|
||||
// Initialize an array with the extended length
|
||||
const res = new Array(nums.length + enlarge).fill(0);
|
||||
// Copy all elements from the original array to the new array
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
res[i] = nums[i];
|
||||
}
|
||||
// Return the extended new array
|
||||
// Return the new, extended array
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Insert element num at index index in the array */
|
||||
/* Insert element num at index `index` in the array */
|
||||
function insert(nums, num, index) {
|
||||
// Move all elements at and after index index backward by one position
|
||||
// Shift all elements at and after index `index` one position to the right
|
||||
for (let i = nums.length - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// Assign num to the element at index index
|
||||
// Assign num to the element at index `index`
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* Remove the element at index index */
|
||||
/* Remove the element at index `index` */
|
||||
function remove(nums, index) {
|
||||
// Move all elements after index index forward by one position
|
||||
// Shift all elements after index `index` one position to the left
|
||||
for (let i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/* Traverse array */
|
||||
/* Traverse the array */
|
||||
function traverse(nums) {
|
||||
let count = 0;
|
||||
// Traverse array by index
|
||||
// Traverse the array by index
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
// Direct traversal of array elements
|
||||
// Iterate directly over the array elements
|
||||
for (const num of nums) {
|
||||
count += num;
|
||||
}
|
||||
}
|
||||
|
||||
/* Find the specified element in the array */
|
||||
/* Find a specified element in the array */
|
||||
function find(nums, target) {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (nums[i] === target) return i;
|
||||
@@ -66,32 +66,32 @@ function find(nums, target) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize array */
|
||||
/* Driver code */
|
||||
/* Initialize the array */
|
||||
const arr = new Array(5).fill(0);
|
||||
console.log('Array arr =', arr);
|
||||
let nums = [1, 3, 2, 5, 4];
|
||||
console.log('Array nums =', nums);
|
||||
|
||||
/* Insert element */
|
||||
/* Random access */
|
||||
let random_num = randomAccess(nums);
|
||||
console.log('Get random element in nums', random_num);
|
||||
console.log('Randomly selected element from nums:', random_num);
|
||||
|
||||
/* Traverse array */
|
||||
/* Extend the length */
|
||||
nums = extend(nums, 3);
|
||||
console.log('Extend array length to 8, get nums =', nums);
|
||||
console.log('Extend the array length to 8, giving nums =', nums);
|
||||
|
||||
/* Insert element */
|
||||
/* Insert an element */
|
||||
insert(nums, 6, 3);
|
||||
console.log('Insert number 6 at index 3, get nums =', nums);
|
||||
console.log('Insert the number 6 at index 3, giving nums =', nums);
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
remove(nums, 2);
|
||||
console.log('Remove element at index 2, get nums =', nums);
|
||||
console.log('Remove the element at index 2, giving nums =', nums);
|
||||
|
||||
/* Traverse array */
|
||||
/* Traverse the array */
|
||||
traverse(nums);
|
||||
|
||||
/* Find element */
|
||||
/* Find an element */
|
||||
let index = find(nums, 3);
|
||||
console.log('Find element 3 in nums, get index =', index);
|
||||
console.log('Find element 3 in nums, giving index =', index);
|
||||
|
||||
@@ -23,7 +23,7 @@ function remove(n0) {
|
||||
n0.next = n1;
|
||||
}
|
||||
|
||||
/* Access the node at index index in the linked list */
|
||||
/* Access the node at index `index` in the linked list */
|
||||
function access(head, index) {
|
||||
for (let i = 0; i < index; i++) {
|
||||
if (!head) {
|
||||
@@ -47,36 +47,36 @@ function find(head, target) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize linked list */
|
||||
// Initialize each node
|
||||
/* Driver code */
|
||||
/* Initialize the linked list */
|
||||
// Initialize the individual nodes
|
||||
const n0 = new ListNode(1);
|
||||
const n1 = new ListNode(3);
|
||||
const n2 = new ListNode(2);
|
||||
const n3 = new ListNode(5);
|
||||
const n4 = new ListNode(4);
|
||||
// Build references between nodes
|
||||
// Set up references between the nodes
|
||||
n0.next = n1;
|
||||
n1.next = n2;
|
||||
n2.next = n3;
|
||||
n3.next = n4;
|
||||
console.log('Initialized linked list is');
|
||||
console.log('The initialized linked list is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
insert(n0, new ListNode(0));
|
||||
console.log('Linked list after inserting node is');
|
||||
console.log('The linked list after inserting a node is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
remove(n0);
|
||||
console.log('Linked list after removing node is');
|
||||
console.log('The linked list after removing a node is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Access node */
|
||||
/* Access a node */
|
||||
const node = access(n0, 3);
|
||||
console.log('Value of node at index 3 in linked list = ' + node.val);
|
||||
console.log('Value of the node at index 3 in the linked list = ' + node.val);
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
const index = find(n0, 2);
|
||||
console.log('Index of node with value 2 in linked list = ' + index);
|
||||
console.log('Index of the node with value 2 in the linked list = ' + index);
|
||||
|
||||
@@ -4,44 +4,44 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Initialize list */
|
||||
/* Initialize the list */
|
||||
const nums = [1, 3, 2, 5, 4];
|
||||
console.log(`List nums = ${nums}`);
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
const num = nums[1];
|
||||
console.log(`Access element at index 1, get num = ${num}`);
|
||||
console.log(`Access the element at index 1, giving num = ${num}`);
|
||||
|
||||
/* Add elements at the end */
|
||||
/* Update an element */
|
||||
nums[1] = 0;
|
||||
console.log(`Update element at index 1 to 0, get nums = ${nums}`);
|
||||
console.log(`Update the element at index 1 to 0, giving nums = ${nums}`);
|
||||
|
||||
/* Remove element */
|
||||
/* Clear the list */
|
||||
nums.length = 0;
|
||||
console.log(`After clearing list, nums = ${nums}`);
|
||||
console.log(`After clearing the list, nums = ${nums}`);
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
/* Append an element at the end */
|
||||
nums.push(1);
|
||||
nums.push(3);
|
||||
nums.push(2);
|
||||
nums.push(5);
|
||||
nums.push(4);
|
||||
console.log(`After adding elements, nums = ${nums}`);
|
||||
console.log(`After appending elements, nums = ${nums}`);
|
||||
|
||||
/* Sort list */
|
||||
/* Insert an element in the middle */
|
||||
nums.splice(3, 0, 6);
|
||||
console.log(`Insert number 6 at index 3, get nums = ${nums}`);
|
||||
console.log(`Insert the number 6 at index 3, giving nums = ${nums}`);
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
nums.splice(3, 1);
|
||||
console.log(`Delete element at index 3, get nums = ${nums}`);
|
||||
console.log(`Remove the element at index 3, giving nums = ${nums}`);
|
||||
|
||||
/* Traverse list by index */
|
||||
/* Traverse the list by index */
|
||||
let count = 0;
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
/* Directly traverse list elements */
|
||||
/* Iterate directly over the list elements */
|
||||
count = 0;
|
||||
for (const x of nums) {
|
||||
count += x;
|
||||
@@ -50,8 +50,8 @@ for (const x of nums) {
|
||||
/* Concatenate two lists */
|
||||
const nums1 = [6, 8, 7, 10, 9];
|
||||
nums.push(...nums1);
|
||||
console.log(`After concatenating list nums1 to nums, get nums = ${nums}`);
|
||||
console.log(`Append list nums1 to nums, giving nums = ${nums}`);
|
||||
|
||||
/* Sort list */
|
||||
/* Sort the list */
|
||||
nums.sort((a, b) => a - b);
|
||||
console.log(`After sorting list, nums = ${nums}`);
|
||||
console.log(`After sorting the list, nums = ${nums}`);
|
||||
|
||||
@@ -6,58 +6,58 @@
|
||||
|
||||
/* List class */
|
||||
class MyList {
|
||||
#arr = new Array(); // Array (stores list elements)
|
||||
#arr = new Array(); // Array (stores the list elements)
|
||||
#capacity = 10; // List capacity
|
||||
#size = 0; // List length (current number of elements)
|
||||
#extendRatio = 2; // Multiple by which the list capacity is extended each time
|
||||
#extendRatio = 2; // Factor by which the list capacity grows each time
|
||||
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
this.#arr = new Array(this.#capacity);
|
||||
}
|
||||
|
||||
/* Get list length (current number of elements) */
|
||||
/* Get the list length (current number of elements)*/
|
||||
size() {
|
||||
return this.#size;
|
||||
}
|
||||
|
||||
/* Get list capacity */
|
||||
/* Get the list capacity */
|
||||
capacity() {
|
||||
return this.#capacity;
|
||||
}
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
get(index) {
|
||||
// If the index is out of bounds, throw an exception, as below
|
||||
// Throw an exception if the index is out of bounds; the same applies below
|
||||
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
|
||||
return this.#arr[index];
|
||||
}
|
||||
|
||||
/* Add elements at the end */
|
||||
/* Update an element */
|
||||
set(index, num) {
|
||||
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
|
||||
this.#arr[index] = num;
|
||||
}
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
/* Append an element at the end */
|
||||
add(num) {
|
||||
// If length equals capacity, need to expand
|
||||
// Grow the capacity if the length equals the capacity
|
||||
if (this.#size === this.#capacity) {
|
||||
this.extendCapacity();
|
||||
}
|
||||
// Add new element to end of list
|
||||
// Append the new element to the end of the list
|
||||
this.#arr[this.#size] = num;
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
/* Sort list */
|
||||
/* Insert an element in the middle */
|
||||
insert(index, num) {
|
||||
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
// Grow the capacity when adding an element would exceed it
|
||||
if (this.#size === this.#capacity) {
|
||||
this.extendCapacity();
|
||||
}
|
||||
// Move all elements after index index forward by one position
|
||||
// Shift all elements at and after index `index` one position to the right
|
||||
for (let j = this.#size - 1; j >= index; j--) {
|
||||
this.#arr[j + 1] = this.#arr[j];
|
||||
}
|
||||
@@ -66,11 +66,11 @@ class MyList {
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
remove(index) {
|
||||
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
|
||||
let num = this.#arr[index];
|
||||
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
|
||||
// Shift all elements after index `index` one position to the left
|
||||
for (let j = index; j < this.#size - 1; j++) {
|
||||
this.#arr[j] = this.#arr[j + 1];
|
||||
}
|
||||
@@ -80,20 +80,20 @@ class MyList {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Grow the list capacity */
|
||||
extendCapacity() {
|
||||
// Create a new array with length extendRatio times the original array and copy the original array to the new array
|
||||
// Create an array extendRatio times the original length and copy the original array into it
|
||||
this.#arr = this.#arr.concat(
|
||||
new Array(this.capacity() * (this.#extendRatio - 1))
|
||||
);
|
||||
// Add elements at the end
|
||||
// Update the list capacity
|
||||
this.#capacity = this.#arr.length;
|
||||
}
|
||||
|
||||
/* Convert list to array */
|
||||
/* Convert the list to an array */
|
||||
toArray() {
|
||||
let size = this.size();
|
||||
// Elements enqueue
|
||||
// Convert only the list elements within the occupied range
|
||||
const arr = new Array(size);
|
||||
for (let i = 0; i < size; i++) {
|
||||
arr[i] = this.get(i);
|
||||
@@ -102,10 +102,10 @@ class MyList {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize list */
|
||||
/* Driver code */
|
||||
/* Initialize the list */
|
||||
const nums = new MyList();
|
||||
/* Direct traversal of list elements */
|
||||
/* Append an element at the end */
|
||||
nums.add(1);
|
||||
nums.add(3);
|
||||
nums.add(2);
|
||||
@@ -115,27 +115,27 @@ console.log(
|
||||
`List nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}`
|
||||
);
|
||||
|
||||
/* Sort list */
|
||||
/* Insert an element in the middle */
|
||||
nums.insert(3, 6);
|
||||
console.log(`Insert number 6 at index 3, get nums = ${nums.toArray()}`);
|
||||
console.log(`Insert the number 6 at index 3, giving nums = ${nums.toArray()}`);
|
||||
|
||||
/* Remove element */
|
||||
/* Remove an element */
|
||||
nums.remove(3);
|
||||
console.log(`Delete element at index 3, get nums = ${nums.toArray()}`);
|
||||
console.log(`Remove the element at index 3, giving nums = ${nums.toArray()}`);
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
const num = nums.get(1);
|
||||
console.log(`Access element at index 1, get num = ${num}`);
|
||||
console.log(`Access the element at index 1, giving num = ${num}`);
|
||||
|
||||
/* Add elements at the end */
|
||||
/* Update an element */
|
||||
nums.set(1, 0);
|
||||
console.log(`Update element at index 1 to 0, get nums = ${nums.toArray()}`);
|
||||
console.log(`Update the element at index 1 to 0, giving nums = ${nums.toArray()}`);
|
||||
|
||||
/* Test capacity expansion mechanism */
|
||||
/* Test capacity growth */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
|
||||
// When i = 5, the list length would exceed its capacity, triggering capacity growth
|
||||
nums.add(i);
|
||||
}
|
||||
console.log(
|
||||
`After expansion, list nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}`
|
||||
`After capacity growth, list nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}`
|
||||
);
|
||||
|
||||
@@ -4,51 +4,51 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
/* Backtracking: n-queens */
|
||||
function backtrack(row, n, state, res, cols, diags1, diags2) {
|
||||
// When all rows are placed, record the solution
|
||||
// Record a solution when a queen has been placed in every row
|
||||
if (row === n) {
|
||||
res.push(state.map((row) => row.slice()));
|
||||
return;
|
||||
}
|
||||
// Traverse all columns
|
||||
// Iterate over all columns
|
||||
for (let col = 0; col < n; col++) {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
// Calculate the main-diagonal and anti-diagonal indices for this square
|
||||
const diag1 = row - col + n - 1;
|
||||
const diag2 = row + col;
|
||||
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
|
||||
// Prune: the square must have no queen in its column, main diagonal, or anti-diagonal
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// Attempt: place the queen in this cell
|
||||
// Try: place a queen on this square
|
||||
state[row][col] = 'Q';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// Place the next row
|
||||
// Place a queen in the next row
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// Backtrack: restore this cell to an empty cell
|
||||
// Backtrack: restore this square to empty
|
||||
state[row][col] = '#';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
/* Solve the n-queens problem */
|
||||
function nQueens(n) {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
// Initialize an n*n board, where 'Q' represents a queen and '#' represents an empty square
|
||||
const state = Array.from({ length: n }, () => Array(n).fill('#'));
|
||||
const cols = Array(n).fill(false); // Record whether there is a queen in the column
|
||||
const diags1 = Array(2 * n - 1).fill(false); // Record whether there is a queen on the main diagonal
|
||||
const diags2 = Array(2 * n - 1).fill(false); // Record whether there is a queen on the anti-diagonal
|
||||
const cols = Array(n).fill(false); // Track whether a column contains a queen
|
||||
const diags1 = Array(2 * n - 1).fill(false); // Track whether a main diagonal contains a queen
|
||||
const diags2 = Array(2 * n - 1).fill(false); // Track whether an anti-diagonal contains a queen
|
||||
const res = [];
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const n = 4;
|
||||
const res = nQueens(n);
|
||||
|
||||
console.log(`Input board size is ${n}`);
|
||||
console.log(`Total queen placement solutions: ${res.length}`);
|
||||
console.log(`Input board side length: ${n}`);
|
||||
console.log(`Number of queen arrangements: ${res.length}`);
|
||||
res.forEach((state) => {
|
||||
console.log('--------------------');
|
||||
state.forEach((row) => console.log(row));
|
||||
|
||||
@@ -4,23 +4,23 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
/* Backtracking: permutations I */
|
||||
function backtrack(state, choices, selected, res) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
// Record a solution when the state length equals the number of elements
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
choices.forEach((choice, i) => {
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
// Prune: do not choose an element more than once
|
||||
if (!selected[i]) {
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
@@ -34,7 +34,7 @@ function permutationsI(nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const nums = [1, 2, 3];
|
||||
const res = permutationsI(nums);
|
||||
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
/* Backtracking: permutations II */
|
||||
function backtrack(state, choices, selected, res) {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
// Record a solution when the state length equals the number of elements
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
const duplicated = new Set();
|
||||
choices.forEach((choice, i) => {
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
// Prune: do not reuse an element or choose the same value again at this depth
|
||||
if (!selected[i] && !duplicated.has(choice)) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.add(choice); // Record the selected element value
|
||||
// Try: make a choice and update the state
|
||||
duplicated.add(choice); // Record the chosen value
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
@@ -36,7 +36,7 @@ function permutationsII(nums) {
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const nums = [1, 2, 2];
|
||||
const res = permutationsII(nums);
|
||||
|
||||
|
||||
@@ -7,22 +7,22 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
/* Preorder traversal: example 1 */
|
||||
function preOrder(root, res) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push(root);
|
||||
}
|
||||
preOrder(root.left, res);
|
||||
preOrder(root.right, res);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
|
||||
@@ -7,15 +7,15 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
/* Preorder traversal: example 2 */
|
||||
function preOrder(root, path, res) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
@@ -24,9 +24,9 @@ function preOrder(root, path, res) {
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
@@ -34,7 +34,7 @@ const path = [];
|
||||
const res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7');
|
||||
console.log('\nOutput all paths from the root to nodes with value 7');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
@@ -7,16 +7,16 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
/* Preorder traversal: example 3 */
|
||||
function preOrder(root, path, res) {
|
||||
// Pruning
|
||||
// Prune
|
||||
if (root === null || root.val === 3) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
// Try
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
@@ -25,9 +25,9 @@ function preOrder(root, path, res) {
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
@@ -35,7 +35,7 @@ const path = [];
|
||||
const res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7, paths do not include nodes with value 3');
|
||||
console.log('\nOutput all paths from the root to nodes with value 7 that contain no node with value 3');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
@@ -7,62 +7,62 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
/* Check whether the current state is a solution */
|
||||
function isSolution(state) {
|
||||
return state && state[state.length - 1]?.val === 7;
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
/* Record the solution */
|
||||
function recordSolution(state, res) {
|
||||
res.push([...state]);
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
/* Check whether the choice is valid in the current state */
|
||||
function isValid(state, choice) {
|
||||
return choice !== null && choice.val !== 3;
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
/* Update the state */
|
||||
function makeChoice(state, choice) {
|
||||
state.push(choice);
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
/* Restore the state */
|
||||
function undoChoice(state) {
|
||||
state.pop();
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
/* Backtracking: example 3 */
|
||||
function backtrack(state, choices, res) {
|
||||
// Check if it is a solution
|
||||
// Check whether this is a solution
|
||||
if (isSolution(state)) {
|
||||
// Record solution
|
||||
// Record the solution
|
||||
recordSolution(state, res);
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (const choice of choices) {
|
||||
// Pruning: check if the choice is valid
|
||||
// Prune: check whether the choice is valid
|
||||
if (isValid(state, choice)) {
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
makeChoice(state, choice);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, [choice.left, choice.right], res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
undoChoice(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
// Driver code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
console.log('\nInitialize the binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
const res = [];
|
||||
backtrack([], [root], res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3');
|
||||
console.log('\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
@@ -4,26 +4,26 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
function backtrack(state, target, choices, start, res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target is zero, so the subset sum equals the original target
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
// Pruning 1: exit the loop if the next choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
// Try: make a choice and update target and start
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
@@ -32,15 +32,15 @@ function backtrack(state, target, choices, start, res) {
|
||||
function subsetSumI(nums, target) {
|
||||
const state = []; // State (subset)
|
||||
nums.sort((a, b) => a - b); // Sort nums
|
||||
const start = 0; // Start point for traversal
|
||||
const res = []; // Result list (subset list)
|
||||
const start = 0; // Starting index for iteration
|
||||
const res = []; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumI(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log(`All subsets with sum ${target}: res = ${JSON.stringify(res)}`);
|
||||
|
||||
@@ -4,41 +4,41 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
/* Backtracking: subset sum I */
|
||||
function backtrack(state, target, total, choices, res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the subset sum equals target
|
||||
if (total === target) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (let i = 0; i < choices.length; i++) {
|
||||
// Pruning: if the subset sum exceeds target, skip this choice
|
||||
// Prune: skip this choice if the subset sum would exceed target
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update element sum total
|
||||
// Try: make a choice and update the sum total
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target, total + choices[i], choices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
/* Solve subset sum I (with duplicate subsets) */
|
||||
function subsetSumINaive(nums, target) {
|
||||
const state = []; // State (subset)
|
||||
const total = 0; // Subset sum
|
||||
const res = []; // Result list (subset list)
|
||||
const res = []; // Result list (list of subsets)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumINaive(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log('Please note that this method outputs results containing duplicate sets');
|
||||
console.log(`All subsets with sum ${target}: res = ${JSON.stringify(res)}`);
|
||||
console.log('Note that this method produces duplicate subsets');
|
||||
|
||||
@@ -4,31 +4,31 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
/* Backtracking: subset sum II */
|
||||
function backtrack(state, target, choices, start, res) {
|
||||
// When the subset sum equals target, record the solution
|
||||
// Record a solution when the remaining target is zero, so the subset sum equals the original target
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start traversing from start to avoid repeatedly selecting the same element
|
||||
// Iterate over all choices
|
||||
// Pruning 2: iterate from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start after the previously chosen index to avoid choosing the same element again
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
// Pruning 1: exit the loop if the next choice exceeds the remaining target
|
||||
// The array is sorted, so later elements are at least as large and would also exceed the remaining target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Pruning 4: if this element equals the left element, it means this search branch is duplicate, skip it directly
|
||||
// Pruning 4: if this element equals its left neighbor at the same search depth, the branch is a duplicate; skip it
|
||||
if (i > start && choices[i] === choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
// Try: make a choice and update target and start
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
// Proceed to the next choice
|
||||
backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
// Backtrack: undo the choice and restore the previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
@@ -37,15 +37,15 @@ function backtrack(state, target, choices, start, res) {
|
||||
function subsetSumII(nums, target) {
|
||||
const state = []; // State (subset)
|
||||
nums.sort((a, b) => a - b); // Sort nums
|
||||
const start = 0; // Start point for traversal
|
||||
const res = []; // Result list (subset list)
|
||||
const start = 0; // Starting index for iteration
|
||||
const res = []; // Result list (list of subsets)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [4, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumII(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log(`All subsets with sum ${target}: res = ${JSON.stringify(res)}`);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: Hello Algo Team
|
||||
*/
|
||||
|
||||
/* Iterative summation */
|
||||
/* Sum using iteration */
|
||||
function sumIter(n) {
|
||||
let res = 0;
|
||||
for (let i = 1; i <= n; i++) {
|
||||
@@ -13,7 +13,7 @@ function sumIter(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Recursive summation */
|
||||
/* Sum using recursion */
|
||||
function sumRecur(n) {
|
||||
if (n === 1) {
|
||||
return 1;
|
||||
@@ -21,7 +21,7 @@ function sumRecur(n) {
|
||||
return n + sumRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Linear loop */
|
||||
/* Linear-time loop */
|
||||
function linearLoop(n) {
|
||||
let res = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -30,7 +30,7 @@ function linearLoop(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Quadratic loop */
|
||||
/* Quadratic-time loop */
|
||||
function quadraticLoop(n) {
|
||||
let res = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -41,7 +41,7 @@ function quadraticLoop(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Logarithmic loop */
|
||||
/* Logarithmic-time loop */
|
||||
function logarithmicLoop(n) {
|
||||
while (n > 1) {
|
||||
n = Math.floor(n / 2);
|
||||
@@ -59,5 +59,5 @@ if (
|
||||
logarithmicLoop(4) !== 1 ||
|
||||
logarithmicLoop(5) !== 1
|
||||
) {
|
||||
throw new Error('complexity exercise check failed');
|
||||
throw new Error('Complexity exercise check failed');
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/* for loop */
|
||||
function forLoop(n) {
|
||||
let res = 0;
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
for (let i = 1; i <= n; i++) {
|
||||
res += i;
|
||||
}
|
||||
@@ -17,11 +17,11 @@ function forLoop(n) {
|
||||
/* while loop */
|
||||
function whileLoop(n) {
|
||||
let res = 0;
|
||||
let i = 1; // Initialize condition variable
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
let i = 1; // Initialize the loop control variable
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
i++; // Update condition variable
|
||||
i++; // Update the loop control variable
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -29,23 +29,23 @@ function whileLoop(n) {
|
||||
/* while loop (two updates) */
|
||||
function whileLoopII(n) {
|
||||
let res = 0;
|
||||
let i = 1; // Initialize condition variable
|
||||
// Sum 1, 4, 10, ...
|
||||
let i = 1; // Initialize the loop control variable
|
||||
// Sum 1, 4, 10, ... in a loop
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
// Update condition variable
|
||||
// Update the loop control variable
|
||||
i++;
|
||||
i *= 2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
/* Nested for loops */
|
||||
function nestedForLoop(n) {
|
||||
let res = '';
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
// Loop over i = 1, 2, ..., n-1, n
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
// Loop over j = 1, 2, ..., n-1, n
|
||||
for (let j = 1; j <= n; j++) {
|
||||
res += `(${i}, ${j}), `;
|
||||
}
|
||||
@@ -53,18 +53,18 @@ function nestedForLoop(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 5;
|
||||
let res;
|
||||
|
||||
res = forLoop(n);
|
||||
console.log(`For loop sum result res = ${res}`);
|
||||
console.log(`Sum from the for loop: res = ${res}`);
|
||||
|
||||
res = whileLoop(n);
|
||||
console.log(`While loop sum result res = ${res}`);
|
||||
console.log(`Sum from the while loop: res = ${res}`);
|
||||
|
||||
res = whileLoopII(n);
|
||||
console.log(`While loop (two updates) sum result res = ${res}`);
|
||||
console.log(`Sum from the while loop with two updates: res = ${res}`);
|
||||
|
||||
const resStr = nestedForLoop(n);
|
||||
console.log(`Nested for loop traversal result ${resStr}`);
|
||||
console.log(`Traversal result from the nested for loops: ${resStr}`);
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
/* Recursion */
|
||||
function recur(n) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (n === 1) return 1;
|
||||
// Recurse: recursive call
|
||||
// Recurse: make a recursive call
|
||||
const res = recur(n - 1);
|
||||
// Return: return result
|
||||
// Unwind: return the result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
@@ -19,14 +19,14 @@ function forLoopRecur(n) {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
const stack = [];
|
||||
let res = 0;
|
||||
// Recurse: recursive call
|
||||
// Recurse: make a recursive call
|
||||
for (let i = n; i > 0; i--) {
|
||||
// Simulate "recurse" with "push"
|
||||
// Simulate recursive calls by pushing onto the stack
|
||||
stack.push(i);
|
||||
}
|
||||
// Return: return result
|
||||
// Unwind: return the result
|
||||
while (stack.length) {
|
||||
// Simulate "return" with "pop"
|
||||
// Simulate unwinding by popping from the stack
|
||||
res += stack.pop();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
@@ -35,35 +35,35 @@ function forLoopRecur(n) {
|
||||
|
||||
/* Tail recursion */
|
||||
function tailRecur(n, res) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (n === 0) return res;
|
||||
// Tail recursive call
|
||||
// Tail-recursive call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
function fib(n) {
|
||||
// Termination condition f(1) = 0, f(2) = 1
|
||||
// Base cases: f(1) = 0, f(2) = 1
|
||||
if (n === 1 || n === 2) return n - 1;
|
||||
// Recursive call f(n) = f(n-1) + f(n-2)
|
||||
// Recursive calls: f(n) = f(n-1) + f(n-2)
|
||||
const res = fib(n - 1) + fib(n - 2);
|
||||
// Return result f(n)
|
||||
// Return the result f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 5;
|
||||
let res;
|
||||
|
||||
res = recur(n);
|
||||
console.log(`Recursion sum result res = ${res}`);
|
||||
console.log(`Sum from the recursive function: res = ${res}`);
|
||||
|
||||
res = forLoopRecur(n);
|
||||
console.log(`Using iteration to simulate recursion sum result res = ${res}`);
|
||||
console.log(`Sum from simulating recursion with iteration: res = ${res}`);
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
console.log(`Tail recursion sum result res = ${res}`);
|
||||
console.log(`Sum from the tail-recursive function: res = ${res}`);
|
||||
|
||||
res = fib(n);
|
||||
console.log(`The ${n}th Fibonacci number is ${res}`);
|
||||
console.log(`Fibonacci term ${n} is ${res}`);
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ function constFunc() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
/* Constant complexity */
|
||||
function constant(n) {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
// Constants, variables, and objects occupy O(1) space
|
||||
const a = 0;
|
||||
const b = 0;
|
||||
const nums = new Array(10000);
|
||||
@@ -25,42 +25,42 @@ function constant(n) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = 0;
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
// Function calls in the loop occupy O(1) space
|
||||
for (let i = 0; i < n; i++) {
|
||||
constFunc();
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
/* Linear complexity */
|
||||
function linear(n) {
|
||||
// Array of length n uses O(n) space
|
||||
// An array of length n uses O(n) space
|
||||
const nums = new Array(n);
|
||||
// A list of length n occupies O(n) space
|
||||
const nodes = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
nodes.push(new ListNode(i));
|
||||
}
|
||||
// A hash table of length n occupies O(n) space
|
||||
// A hash table with n entries occupies O(n) space
|
||||
const map = new Map();
|
||||
for (let i = 0; i < n; i++) {
|
||||
map.set(i, i.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
/* Linear complexity (recursive implementation) */
|
||||
function linearRecur(n) {
|
||||
console.log(`Recursion n = ${n}`);
|
||||
console.log(`Recursive call with n = ${n}`);
|
||||
if (n === 1) return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
/* Quadratic complexity */
|
||||
function quadratic(n) {
|
||||
// Matrix uses O(n^2) space
|
||||
// The matrix uses O(n^2) space
|
||||
const numMatrix = Array(n)
|
||||
.fill(null)
|
||||
.map(() => Array(n).fill(null));
|
||||
// 2D list uses O(n^2) space
|
||||
// The two-dimensional list occupies O(n^2) space
|
||||
const numList = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const tmp = [];
|
||||
@@ -71,15 +71,15 @@ function quadratic(n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Quadratic order (recursive implementation) */
|
||||
/* Quadratic complexity (recursive implementation) */
|
||||
function quadraticRecur(n) {
|
||||
if (n <= 0) return 0;
|
||||
const nums = new Array(n);
|
||||
console.log(`In recursion n = ${n}, nums length = ${nums.length}`);
|
||||
console.log(`In the recursive call with n = ${n}, nums has length ${nums.length}`);
|
||||
return quadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Exponential complexity (building a perfect binary tree) */
|
||||
function buildTree(n) {
|
||||
if (n === 0) return null;
|
||||
const root = new TreeNode(0);
|
||||
@@ -88,16 +88,16 @@ function buildTree(n) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 5;
|
||||
// Constant order
|
||||
// Constant complexity
|
||||
constant(n);
|
||||
// Linear order
|
||||
// Linear complexity
|
||||
linear(n);
|
||||
linearRecur(n);
|
||||
// Exponential order
|
||||
// Quadratic complexity
|
||||
quadratic(n);
|
||||
quadraticRecur(n);
|
||||
// Exponential order
|
||||
// Exponential complexity
|
||||
const root = buildTree(n);
|
||||
printTree(root);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: RiverTwilight (contact@rene.wang)
|
||||
*/
|
||||
|
||||
/* Constant order */
|
||||
/* Constant complexity */
|
||||
function constant(n) {
|
||||
let count = 0;
|
||||
const size = 100000;
|
||||
@@ -12,27 +12,27 @@ function constant(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
/* Linear complexity */
|
||||
function linear(n) {
|
||||
let count = 0;
|
||||
for (let i = 0; i < n; i++) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order (traversing array) */
|
||||
/* Linear complexity (array traversal) */
|
||||
function arrayTraversal(nums) {
|
||||
let count = 0;
|
||||
// Number of iterations is proportional to the array length
|
||||
// The number of iterations is proportional to the array length
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
/* Quadratic complexity */
|
||||
function quadratic(n) {
|
||||
let count = 0;
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
// The number of iterations is proportional to the square of the input size n
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
count++;
|
||||
@@ -41,30 +41,30 @@ function quadratic(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Quadratic order (bubble sort) */
|
||||
/* Quadratic complexity (bubble sort) */
|
||||
function bubbleSort(nums) {
|
||||
let count = 0; // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
count += 3; // Element swap includes 3 unit operations
|
||||
count += 3; // Swapping two elements takes 3 elementary operations
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (loop implementation) */
|
||||
/* Exponential complexity (iterative implementation) */
|
||||
function exponential(n) {
|
||||
let count = 0,
|
||||
base = 1;
|
||||
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
// Each cell divides into two per round, giving the sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < base; j++) {
|
||||
count++;
|
||||
@@ -75,13 +75,13 @@ function exponential(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (recursive implementation) */
|
||||
/* Exponential complexity (recursive implementation) */
|
||||
function expRecur(n) {
|
||||
if (n === 1) return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
/* Logarithmic complexity (iterative implementation) */
|
||||
function logarithmic(n) {
|
||||
let count = 0;
|
||||
while (n > 1) {
|
||||
@@ -91,13 +91,13 @@ function logarithmic(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
/* Logarithmic complexity (recursive implementation) */
|
||||
function logRecur(n) {
|
||||
if (n <= 1) return 0;
|
||||
return logRecur(n / 2) + 1;
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
/* Linearithmic complexity */
|
||||
function linearLogRecur(n) {
|
||||
if (n <= 1) return 1;
|
||||
let count = linearLogRecur(n / 2) + linearLogRecur(n / 2);
|
||||
@@ -107,49 +107,49 @@ function linearLogRecur(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
/* Factorial complexity (recursive implementation) */
|
||||
function factorialRecur(n) {
|
||||
if (n === 0) return 1;
|
||||
let count = 0;
|
||||
// Split from 1 into n
|
||||
// Split one problem into n subproblems
|
||||
for (let i = 0; i < n; i++) {
|
||||
count += factorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
/* Driver code */
|
||||
// Try different values of n to see how the operation count grows for each complexity
|
||||
const n = 8;
|
||||
console.log('Input data size n = ' + n);
|
||||
console.log('Input size n = ' + n);
|
||||
|
||||
let count = constant(n);
|
||||
console.log('Constant order operation count = ' + count);
|
||||
console.log('Operation count for constant complexity = ' + count);
|
||||
|
||||
count = linear(n);
|
||||
console.log('Linear order operation count = ' + count);
|
||||
console.log('Operation count for linear complexity = ' + count);
|
||||
count = arrayTraversal(new Array(n));
|
||||
console.log('Linear order (array traversal) operation count = ' + count);
|
||||
console.log('Operation count for linear complexity (array traversal) = ' + count);
|
||||
|
||||
count = quadratic(n);
|
||||
console.log('Quadratic order operation count = ' + count);
|
||||
console.log('Operation count for quadratic complexity = ' + count);
|
||||
let nums = new Array(n);
|
||||
for (let i = 0; i < n; i++) nums[i] = n - i; // [n,n-1,...,2,1]
|
||||
count = bubbleSort(nums);
|
||||
console.log('Quadratic order (bubble sort) operation count = ' + count);
|
||||
console.log('Operation count for quadratic complexity (bubble sort) = ' + count);
|
||||
|
||||
count = exponential(n);
|
||||
console.log('Exponential order (loop implementation) operation count = ' + count);
|
||||
console.log('Operation count for exponential complexity (iterative implementation) = ' + count);
|
||||
count = expRecur(n);
|
||||
console.log('Exponential order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for exponential complexity (recursive implementation) = ' + count);
|
||||
|
||||
count = logarithmic(n);
|
||||
console.log('Logarithmic order (loop implementation) operation count = ' + count);
|
||||
console.log('Operation count for logarithmic complexity (iterative implementation) = ' + count);
|
||||
count = logRecur(n);
|
||||
console.log('Logarithmic order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for logarithmic complexity (recursive implementation) = ' + count);
|
||||
|
||||
count = linearLogRecur(n);
|
||||
console.log('Linearithmic order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for linearithmic complexity (recursive implementation) = ' + count);
|
||||
|
||||
count = factorialRecur(n);
|
||||
console.log('Factorial order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for factorial complexity (recursive implementation) = ' + count);
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
* Author: RiverTwilight (contact@rene.wang)
|
||||
*/
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
/* Generate an array containing { 1, 2, ..., n } in shuffled order */
|
||||
function randomNumbers(n) {
|
||||
const nums = Array(n);
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
// Generate the array nums = { 1, 2, 3, ..., n }
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
// Randomly shuffle array elements
|
||||
// Randomly shuffle the array elements
|
||||
for (let i = 0; i < n; i++) {
|
||||
const r = Math.floor(Math.random() * (i + 1));
|
||||
const temp = nums[i];
|
||||
@@ -21,11 +21,11 @@ function randomNumbers(n) {
|
||||
return nums;
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
/* Find the index of the number 1 in array nums */
|
||||
function findOne(nums) {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
// When element 1 is at the head of the array, best time complexity O(1) is achieved
|
||||
// When element 1 is at the tail of the array, worst time complexity O(n) is achieved
|
||||
// When 1 is at the start of the array, the best-case time complexity is O(1)
|
||||
// When 1 is at the end of the array, the worst-case time complexity is O(n)
|
||||
if (nums[i] === 1) {
|
||||
return i;
|
||||
}
|
||||
@@ -33,11 +33,11 @@ function findOne(nums) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const n = 100;
|
||||
const nums = randomNumbers(n);
|
||||
const index = findOne(nums);
|
||||
console.log('\nArray [ 1, 2, ..., n ] after shuffling = [' + nums.join(', ') + ']');
|
||||
console.log('Index of number 1 is ' + index);
|
||||
console.log('The index of the number 1 is ' + index);
|
||||
}
|
||||
|
||||
@@ -6,20 +6,20 @@
|
||||
|
||||
/* Binary search: problem f(i, j) */
|
||||
function dfs(nums, target, i, j) {
|
||||
// If the interval is empty, it means there is no target element, return -1
|
||||
// If the interval is empty, the target is absent; return -1
|
||||
if (i > j) {
|
||||
return -1;
|
||||
}
|
||||
// Calculate the midpoint index m
|
||||
const m = i + ((j - i) >> 1);
|
||||
if (nums[m] < target) {
|
||||
// Recursion subproblem f(m+1, j)
|
||||
// Recurse on subproblem f(m+1, j)
|
||||
return dfs(nums, target, m + 1, j);
|
||||
} else if (nums[m] > target) {
|
||||
// Recursion subproblem f(i, m-1)
|
||||
// Recurse on subproblem f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1);
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
// The target element was found; return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -27,13 +27,13 @@ function dfs(nums, target, i, j) {
|
||||
/* Binary search */
|
||||
function binarySearch(nums, target) {
|
||||
const n = nums.length;
|
||||
// Solve the problem f(0, n-1)
|
||||
// Solve problem f(0, n-1)
|
||||
return dfs(nums, target, 0, n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const target = 6;
|
||||
const nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
// Binary search (closed interval on both sides)
|
||||
// Binary search (closed interval)
|
||||
const index = binarySearch(nums, target);
|
||||
console.log(`Index of target element 6 is ${index}`);
|
||||
console.log(`Index of target element 6 = ${index}`);
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
const { TreeNode } = require('../modules/TreeNode');
|
||||
|
||||
/* Build binary tree: divide and conquer */
|
||||
/* Build a binary tree: divide and conquer */
|
||||
function dfs(preorder, inorderMap, i, l, r) {
|
||||
// Terminate when the subtree interval is empty
|
||||
// Stop when the subtree interval is empty
|
||||
if (r - l < 0) return null;
|
||||
// Initialize the root node
|
||||
const root = new TreeNode(preorder[i]);
|
||||
// Query m to divide the left and right subtrees
|
||||
// Look up m to separate the left and right subtrees
|
||||
const m = inorderMap.get(preorder[i]);
|
||||
// Subproblem: build the left subtree
|
||||
root.left = dfs(preorder, inorderMap, i + 1, l, m - 1);
|
||||
@@ -23,9 +23,9 @@ function dfs(preorder, inorderMap, i, l, r) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Build binary tree */
|
||||
/* Build a binary tree */
|
||||
function buildTree(preorder, inorder) {
|
||||
// Initialize hash map, storing the mapping from inorder elements to indices
|
||||
// Initialize a hash table mapping each element in inorder to its index
|
||||
let inorderMap = new Map();
|
||||
for (let i = 0; i < inorder.length; i++) {
|
||||
inorderMap.set(inorder[i], i);
|
||||
@@ -34,7 +34,7 @@ function buildTree(preorder, inorder) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const preorder = [3, 9, 2, 1, 7];
|
||||
const inorder = [9, 3, 1, 2, 7];
|
||||
console.log('Preorder traversal = ' + JSON.stringify(preorder));
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: Hello Algo Team
|
||||
*/
|
||||
|
||||
/* Exponentiation by squaring */
|
||||
/* Fast exponentiation */
|
||||
function fastPow(x, n) {
|
||||
if (n === 0) {
|
||||
return 1;
|
||||
@@ -17,5 +17,5 @@ function fastPow(x, n) {
|
||||
}
|
||||
|
||||
if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) {
|
||||
throw new Error('fast power check failed');
|
||||
throw new Error('Fast power check failed');
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Move a disk */
|
||||
/* Move one disk */
|
||||
function move(src, tar) {
|
||||
// Take out a disk from the top of src
|
||||
// Take a disk from the top of src
|
||||
const pan = src.pop();
|
||||
// Place the disk on top of tar
|
||||
tar.push(pan);
|
||||
@@ -14,14 +14,14 @@ function move(src, tar) {
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
function dfs(i, src, buf, tar) {
|
||||
// If there is only one disk left in src, move it directly to tar
|
||||
// If only one disk remains to be moved from src, move it directly to tar
|
||||
if (i === 1) {
|
||||
move(src, tar);
|
||||
return;
|
||||
}
|
||||
// Subproblem f(i-1): move the top i-1 disks from src to buf using tar
|
||||
dfs(i - 1, src, tar, buf);
|
||||
// Subproblem f(1): move the remaining disk from src to tar
|
||||
// Subproblem f(1): move the remaining disk of this subproblem from src to tar
|
||||
move(src, tar);
|
||||
// Subproblem f(i-1): move the top i-1 disks from buf to tar using src
|
||||
dfs(i - 1, buf, src, tar);
|
||||
@@ -34,19 +34,19 @@ function solveHanota(A, B, C) {
|
||||
dfs(n, A, B, C);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// The tail of the list is the top of the rod
|
||||
/* Driver code */
|
||||
// The end of each list represents the top of the peg
|
||||
const A = [5, 4, 3, 2, 1];
|
||||
const B = [];
|
||||
const C = [];
|
||||
console.log('In initial state:');
|
||||
console.log('Initial state:');
|
||||
console.log(`A = ${JSON.stringify(A)}`);
|
||||
console.log(`B = ${JSON.stringify(B)}`);
|
||||
console.log(`C = ${JSON.stringify(C)}`);
|
||||
|
||||
solveHanota(A, B, C);
|
||||
|
||||
console.log('After disk movement is complete:');
|
||||
console.log('After moving the disks:');
|
||||
console.log(`A = ${JSON.stringify(A)}`);
|
||||
console.log(`B = ${JSON.stringify(B)}`);
|
||||
console.log(`C = ${JSON.stringify(C)}`);
|
||||
|
||||
@@ -6,29 +6,29 @@
|
||||
|
||||
/* Backtracking */
|
||||
function backtrack(choices, state, n, res) {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
// When step n is reached, increase the number of ways by 1
|
||||
if (state === n) res.set(0, res.get(0) + 1);
|
||||
// Traverse all choices
|
||||
// Iterate over all choices
|
||||
for (const choice of choices) {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
// Prune: do not go beyond step n
|
||||
if (state + choice > n) continue;
|
||||
// Attempt: make choice, update state
|
||||
// Try: make a choice and update the state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
/* Climbing stairs: backtracking */
|
||||
function climbingStairsBacktrack(n) {
|
||||
const choices = [1, 2]; // Can choose to climb up 1 or 2 stairs
|
||||
const state = 0; // Start climbing from the 0-th stair
|
||||
const choices = [1, 2]; // Choose to climb 1 or 2 steps
|
||||
const state = 0; // Start climbing from step 0
|
||||
const res = new Map();
|
||||
res.set(0, 0); // Use res[0] to record the solution count
|
||||
res.set(0, 0); // Store the number of ways at key 0 in res
|
||||
backtrack(choices, state, n, res);
|
||||
return res.get(0);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsBacktrack(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
/* Climbing stairs with constraints: dynamic programming */
|
||||
function climbingStairsConstraintDP(n) {
|
||||
if (n === 1 || n === 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
const dp = Array.from(new Array(n + 1), () => new Array(3));
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (let i = 3; i <= n; i++) {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
@@ -24,7 +24,7 @@ function climbingStairsConstraintDP(n) {
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsConstraintDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -6,19 +6,19 @@
|
||||
|
||||
/* Search */
|
||||
function dfs(i) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i === 1 || i === 2) return i;
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
const count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
/* Climbing stairs: search */
|
||||
function climbingStairsDFS(n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFS(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
/* Memoized search */
|
||||
function dfs(i, mem) {
|
||||
// Known dp[1] and dp[2], return them
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i === 1 || i === 2) return i;
|
||||
// If record dp[i] exists, return it directly
|
||||
// If dp[i] has been recorded, return it directly
|
||||
if (mem[i] != -1) return mem[i];
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
const count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
@@ -17,14 +17,14 @@ function dfs(i, mem) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
/* Climbing stairs: memoized search */
|
||||
function climbingStairsDFSMem(n) {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
// mem[i] stores the number of ways to reach step i; -1 means no result has been recorded
|
||||
const mem = new Array(n + 1).fill(-1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFSMem(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,22 +4,22 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
/* Climbing stairs: dynamic programming */
|
||||
function climbingStairsDP(n) {
|
||||
if (n === 1 || n === 2) return n;
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
const dp = new Array(n + 1).fill(-1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (let i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
/* Climbing stairs: space-optimized dynamic programming */
|
||||
function climbingStairsDPComp(n) {
|
||||
if (n === 1 || n === 2) return n;
|
||||
let a = 1,
|
||||
@@ -32,9 +32,9 @@ function climbingStairsDPComp(n) {
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 9;
|
||||
let res = climbingStairsDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
res = climbingStairsDPComp(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
console.log(`Number of ways to climb ${n} stairs: ${res}`);
|
||||
|
||||
@@ -4,26 +4,26 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
/* Coin change: dynamic programming */
|
||||
function coinChangeDP(coins, amt) {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -31,21 +31,21 @@ function coinChangeDP(coins, amt) {
|
||||
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
/* Coin change: space-optimized dynamic programming */
|
||||
function coinChangeDPComp(coins, amt) {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
@@ -53,14 +53,14 @@ function coinChangeDPComp(coins, amt) {
|
||||
return dp[amt] !== MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const coins = [1, 2, 5];
|
||||
const amt = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coinChangeDP(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
console.log(`Minimum number of coins needed to make the target amount: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
console.log(`Minimum number of coins needed to make the target amount: ${res}`);
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
/* Coin change II: dynamic programming */
|
||||
function coinChangeIIDP(coins, amt) {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// Initialize first column
|
||||
// Initialize the first column
|
||||
for (let i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
// Add the numbers of ways without and with coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
@@ -30,20 +30,20 @@ function coinChangeIIDP(coins, amt) {
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
/* Coin change II: space-optimized dynamic programming */
|
||||
function coinChangeIIDPComp(coins, amt) {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => 0);
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
// Add the numbers of ways without and with coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
@@ -51,14 +51,14 @@ function coinChangeIIDPComp(coins, amt) {
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const coins = [1, 2, 5];
|
||||
const amt = 5;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coinChangeIIDP(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
console.log(`Number of coin combinations that make the target amount: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
console.log(`Number of coin combinations that make the target amount: ${res}`);
|
||||
|
||||
@@ -4,76 +4,76 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
/* Edit distance: brute-force search */
|
||||
function editDistanceDFS(s, t, i, j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If the current prefixes of both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
// If the current prefix of s is empty, return the current prefix length j of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
// If the current prefix of t is empty, return the current prefix length i of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1))
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
const insert = editDistanceDFS(s, t, i, j - 1);
|
||||
const del = editDistanceDFS(s, t, i - 1, j);
|
||||
const replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Return minimum edit steps
|
||||
// Return the minimum number of edits
|
||||
return Math.min(insert, del, replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
/* Edit distance: memoized search */
|
||||
function editDistanceDFSMem(s, t, mem, i, j) {
|
||||
// If both s and t are empty, return 0
|
||||
// If the current prefixes of both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
// If the current prefix of s is empty, return the current prefix length j of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
// If the current prefix of t is empty, return the current prefix length i of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] !== -1) return mem[i][j];
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1))
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
const insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
const del = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
const replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Record and return minimum edit steps
|
||||
// Record and return the minimum number of edits
|
||||
mem[i][j] = Math.min(insert, del, replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
/* Edit distance: dynamic programming */
|
||||
function editDistanceDP(s, t) {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
|
||||
// State transition: first row and first column
|
||||
// State transitions: first row and first column
|
||||
for (let i = 1; i <= n; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let j = 1; j <= m; j++) {
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[i][j] =
|
||||
Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
@@ -82,31 +82,31 @@ function editDistanceDP(s, t) {
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
/* Edit distance: space-optimized dynamic programming */
|
||||
function editDistanceDPComp(s, t) {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = new Array(m + 1).fill(0);
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
let leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (let j = 1; j <= m; j++) {
|
||||
const temp = dp[j];
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
@@ -119,17 +119,17 @@ const n = s.length,
|
||||
|
||||
// Brute-force search
|
||||
let res = editDistanceDFS(s, t, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
const mem = Array.from(new Array(n + 1), () => new Array(m + 1).fill(-1));
|
||||
res = editDistanceDFSMem(s, t, mem, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
console.log(`Minimum number of edits to transform ${s} into ${t}: ${res}`);
|
||||
|
||||
@@ -4,61 +4,61 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
/* 0-1 knapsack: brute-force search */
|
||||
function knapsackDFS(wgt, val, i, c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
const no = knapsackDFS(wgt, val, i - 1, c);
|
||||
const yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Return the larger value of the two options
|
||||
// Return the larger value from the two choices
|
||||
return Math.max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
/* 0-1 knapsack: memoized search */
|
||||
function knapsackDFSMem(wgt, val, mem, i, c) {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][c] !== -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
const no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
const yes =
|
||||
knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Record and return the larger value of the two options
|
||||
// Record and return the larger value from the two choices
|
||||
mem[i][c] = Math.max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
/* 0-1 knapsack: dynamic programming */
|
||||
function knapsackDP(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array(n + 1)
|
||||
.fill(0)
|
||||
.map(() => Array(cap + 1).fill(0));
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i - 1][c - wgt[i - 1]] + val[i - 1]
|
||||
@@ -69,17 +69,17 @@ function knapsackDP(wgt, val, cap) {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Space-optimized dynamic programming */
|
||||
/* 0-1 knapsack: space-optimized dynamic programming */
|
||||
function knapsackDPComp(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array(cap + 1).fill(0);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
// Traverse in decreasing order
|
||||
for (let c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,7 @@ function knapsackDPComp(wgt, val, cap) {
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const wgt = [10, 20, 30, 40, 50];
|
||||
const val = [50, 120, 150, 210, 240];
|
||||
const cap = 50;
|
||||
@@ -95,19 +95,19 @@ const n = wgt.length;
|
||||
|
||||
// Brute-force search
|
||||
let res = knapsackDFS(wgt, val, n, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
const mem = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => -1)
|
||||
);
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
/* Minimum cost to climb stairs: dynamic programming */
|
||||
function minCostClimbingStairsDP(cost) {
|
||||
const n = cost.length - 1;
|
||||
if (n === 1 || n === 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
const dp = new Array(n + 1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (let i = 3; i <= n; i++) {
|
||||
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
/* Minimum cost to climb stairs: space-optimized dynamic programming */
|
||||
function minCostClimbingStairsDPComp(cost) {
|
||||
const n = cost.length - 1;
|
||||
if (n === 1 || n === 2) {
|
||||
@@ -38,12 +38,12 @@ function minCostClimbingStairsDPComp(cost) {
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
console.log('Input stair cost list is:', cost);
|
||||
console.log('Input list of stair costs:', cost);
|
||||
|
||||
let res = minCostClimbingStairsDP(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
console.log(`Minimum cost to climb the stairs: ${res}`);
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
console.log(`Minimum cost to climb the stairs: ${res}`);
|
||||
|
||||
@@ -4,63 +4,63 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
/* Minimum path sum: brute-force search */
|
||||
function minPathSumDFS(grid, i, j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
// Stop searching at the top-left cell
|
||||
if (i === 0 && j === 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
if (i < 0 || j < 0) {
|
||||
return Infinity;
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
|
||||
const up = minPathSumDFS(grid, i - 1, j);
|
||||
const left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
return Math.min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
/* Minimum path sum: memoized search */
|
||||
function minPathSumDFSMem(grid, mem, i, j) {
|
||||
// If it's the top-left cell, terminate the search
|
||||
// Stop searching at the top-left cell
|
||||
if (i === 0 && j === 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
// If a row or column index is out of bounds, return a cost of +∞
|
||||
if (i < 0 || j < 0) {
|
||||
return Infinity;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] !== -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
// Minimum path costs to the cells on the left and above
|
||||
const up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
const left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
// Record and return the minimum path cost from the top-left corner to (i, j)
|
||||
mem[i][j] = Math.min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
/* Minimum path sum: dynamic programming */
|
||||
function minPathSumDP(grid) {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => 0)
|
||||
);
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
for (let i = 1; i < n; i++) {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
// State transitions: remaining rows and columns
|
||||
for (let i = 1; i < n; i++) {
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
@@ -69,22 +69,22 @@ function minPathSumDP(grid) {
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
/* Minimum path sum: space-optimized dynamic programming */
|
||||
function minPathSumDPComp(grid) {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = new Array(m);
|
||||
// State transition: first row
|
||||
// State transitions: first row
|
||||
dp[0] = grid[0][0];
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
// State transitions: remaining rows
|
||||
for (let i = 1; i < n; i++) {
|
||||
// State transition: first column
|
||||
// State transitions: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transition: rest of the columns
|
||||
// State transitions: remaining columns
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
@@ -92,7 +92,7 @@ function minPathSumDPComp(grid) {
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const grid = [
|
||||
[1, 3, 1, 5],
|
||||
[2, 2, 4, 2],
|
||||
@@ -103,19 +103,19 @@ const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Brute-force search
|
||||
let res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
// Memoization search
|
||||
// Memoized search
|
||||
const mem = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => -1)
|
||||
);
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
console.log(`Minimum path sum from the top-left to the bottom-right: ${res}`);
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
/* Unbounded knapsack: dynamic programming */
|
||||
function unboundedKnapsackDP(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => 0)
|
||||
);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i][c - wgt[i - 1]] + val[i - 1]
|
||||
@@ -29,19 +29,19 @@ function unboundedKnapsackDP(wgt, val, cap) {
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
/* Unbounded knapsack: space-optimized dynamic programming */
|
||||
function unboundedKnapsackDPComp(wgt, val, cap) {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
// Initialize the dp table
|
||||
const dp = Array.from({ length: cap + 1 }, () => 0);
|
||||
// State transition
|
||||
// State transitions
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
@@ -49,15 +49,15 @@ function unboundedKnapsackDPComp(wgt, val, cap) {
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const wgt = [1, 2, 3];
|
||||
const val = [5, 11, 15];
|
||||
const cap = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = unboundedKnapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
const { Vertex } = require('../modules/Vertex');
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
/* Undirected graph class implemented with an adjacency list */
|
||||
class GraphAdjList {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
// Adjacency list: key is a vertex, value is the list of all its neighbors
|
||||
adjList;
|
||||
|
||||
/* Constructor */
|
||||
@@ -27,21 +27,21 @@ class GraphAdjList {
|
||||
return this.adjList.size;
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
/* Add an edge */
|
||||
addEdge(vet1, vet2) {
|
||||
if (
|
||||
!this.adjList.has(vet1) ||
|
||||
!this.adjList.has(vet2) ||
|
||||
vet1 === vet2
|
||||
) {
|
||||
throw new Error('Illegal Argument Exception');
|
||||
throw new Error('Invalid argument');
|
||||
}
|
||||
// Add edge vet1 - vet2
|
||||
this.adjList.get(vet1).push(vet2);
|
||||
this.adjList.get(vet2).push(vet1);
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
/* Remove an edge */
|
||||
removeEdge(vet1, vet2) {
|
||||
if (
|
||||
!this.adjList.has(vet1) ||
|
||||
@@ -49,28 +49,28 @@ class GraphAdjList {
|
||||
vet1 === vet2 ||
|
||||
this.adjList.get(vet1).indexOf(vet2) === -1
|
||||
) {
|
||||
throw new Error('Illegal Argument Exception');
|
||||
throw new Error('Invalid argument');
|
||||
}
|
||||
// Remove edge vet1 - vet2
|
||||
this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1);
|
||||
this.adjList.get(vet2).splice(this.adjList.get(vet2).indexOf(vet1), 1);
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
addVertex(vet) {
|
||||
if (this.adjList.has(vet)) return;
|
||||
// Add a new linked list in the adjacency list
|
||||
// Add a new list to the adjacency list
|
||||
this.adjList.set(vet, []);
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
removeVertex(vet) {
|
||||
if (!this.adjList.has(vet)) {
|
||||
throw new Error('Illegal Argument Exception');
|
||||
throw new Error('Invalid argument');
|
||||
}
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
// Remove the list corresponding to vertex vet from the adjacency list
|
||||
this.adjList.delete(vet);
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
// Traverse the lists of the other vertices and remove all edges incident to vet
|
||||
for (const set of this.adjList.values()) {
|
||||
const index = set.indexOf(vet);
|
||||
if (index > -1) {
|
||||
@@ -79,7 +79,7 @@ class GraphAdjList {
|
||||
}
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
/* Print the adjacency list */
|
||||
print() {
|
||||
console.log('Adjacency list =');
|
||||
for (const [key, value] of this.adjList) {
|
||||
@@ -93,8 +93,8 @@ class GraphAdjList {
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
/* Driver code */
|
||||
/* Initialize the undirected graph */
|
||||
const v0 = new Vertex(1),
|
||||
v1 = new Vertex(3),
|
||||
v2 = new Vertex(2),
|
||||
@@ -109,31 +109,31 @@ if (require.main === module) {
|
||||
[v3, v4],
|
||||
];
|
||||
const graph = new GraphAdjList(edges);
|
||||
console.log('\nAfter initialization, graph is');
|
||||
console.log('\nGraph after initialization:');
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 2 are v0, v2
|
||||
/* Add an edge */
|
||||
// Vertices 1 and 2 are v0 and v2
|
||||
graph.addEdge(v0, v2);
|
||||
console.log('\nAfter adding edge 1-2, graph is');
|
||||
console.log('\nGraph after adding edge 1-2:');
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 are v0, v1
|
||||
/* Remove an edge */
|
||||
// Vertices 1 and 3 are v0 and v1
|
||||
graph.removeEdge(v0, v1);
|
||||
console.log('\nAfter removing edge 1-3, graph is');
|
||||
console.log('\nGraph after removing edge 1-3:');
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
const v5 = new Vertex(6);
|
||||
graph.addVertex(v5);
|
||||
console.log('\nAfter adding vertex 6, graph is');
|
||||
console.log('\nGraph after adding vertex 6:');
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
// Vertex 3 is v1
|
||||
graph.removeVertex(v1);
|
||||
console.log('\nAfter removing vertex 3, graph is');
|
||||
console.log('\nGraph after removing vertex 3:');
|
||||
graph.print();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
/* Undirected graph class implemented with an adjacency matrix */
|
||||
class GraphAdjMat {
|
||||
vertices; // Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
|
||||
adjMat; // Adjacency matrix, where the row and column indices correspond to the "vertex index"
|
||||
vertices; // Vertex list: elements are vertex values, and indices are vertex indices
|
||||
adjMat; // Adjacency matrix: row and column indices correspond to vertex indices
|
||||
|
||||
/* Constructor */
|
||||
constructor(vertices, edges) {
|
||||
this.vertices = [];
|
||||
this.adjMat = [];
|
||||
// Add vertex
|
||||
// Add a vertex
|
||||
for (const val of vertices) {
|
||||
this.addVertex(val);
|
||||
}
|
||||
// Add edge
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
// Add an edge
|
||||
// Note that the entries in edges are vertex indices, corresponding to element indices in vertices
|
||||
for (const e of edges) {
|
||||
this.addEdge(e[0], e[1]);
|
||||
}
|
||||
@@ -29,10 +29,10 @@ class GraphAdjMat {
|
||||
return this.vertices.length;
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
addVertex(val) {
|
||||
const n = this.size();
|
||||
// Add the value of the new vertex to the vertex list
|
||||
// Append the new vertex value to the vertex list
|
||||
this.vertices.push(val);
|
||||
// Add a row to the adjacency matrix
|
||||
const newRow = [];
|
||||
@@ -46,55 +46,55 @@ class GraphAdjMat {
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
removeVertex(index) {
|
||||
if (index >= this.size()) {
|
||||
throw new RangeError('Index Out Of Bounds Exception');
|
||||
throw new RangeError('Index out of bounds');
|
||||
}
|
||||
// Remove the vertex at index from the vertex list
|
||||
// Remove the vertex at index `index` from the vertex list
|
||||
this.vertices.splice(index, 1);
|
||||
|
||||
// Remove the row at index from the adjacency matrix
|
||||
// Remove row `index` from the adjacency matrix
|
||||
this.adjMat.splice(index, 1);
|
||||
// Remove the column at index from the adjacency matrix
|
||||
// Remove column `index` from the adjacency matrix
|
||||
for (const row of this.adjMat) {
|
||||
row.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
/* Add an edge */
|
||||
// Parameters i and j are element indices in vertices
|
||||
addEdge(i, j) {
|
||||
// Handle index out of bounds and equality
|
||||
// Handle out-of-bounds or equal indices
|
||||
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
|
||||
throw new RangeError('Index Out Of Bounds Exception');
|
||||
throw new RangeError('Index out of bounds');
|
||||
}
|
||||
// In undirected graph, adjacency matrix is symmetric about main diagonal, i.e., satisfies (i, j) === (j, i)
|
||||
// In an undirected graph, the adjacency matrix is symmetric about its main diagonal: (i, j) === (j, i)
|
||||
this.adjMat[i][j] = 1;
|
||||
this.adjMat[j][i] = 1;
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
/* Remove an edge */
|
||||
// Parameters i and j are element indices in vertices
|
||||
removeEdge(i, j) {
|
||||
// Handle index out of bounds and equality
|
||||
// Handle out-of-bounds or equal indices
|
||||
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
|
||||
throw new RangeError('Index Out Of Bounds Exception');
|
||||
throw new RangeError('Index out of bounds');
|
||||
}
|
||||
this.adjMat[i][j] = 0;
|
||||
this.adjMat[j][i] = 0;
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
/* Print the adjacency matrix */
|
||||
print() {
|
||||
console.log('Vertex list = ', this.vertices);
|
||||
console.log('Adjacency matrix =', this.adjMat);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
/* Driver code */
|
||||
/* Initialize the undirected graph */
|
||||
// Note that the entries in edges are vertex indices, corresponding to element indices in vertices
|
||||
const vertices = [1, 3, 2, 5, 4];
|
||||
const edges = [
|
||||
[0, 1],
|
||||
@@ -105,28 +105,28 @@ const edges = [
|
||||
[3, 4],
|
||||
];
|
||||
const graph = new GraphAdjMat(vertices, edges);
|
||||
console.log('\nAfter initialization, graph is');
|
||||
console.log('\nGraph after initialization:');
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Add vertex
|
||||
/* Add an edge */
|
||||
// Vertices 1 and 2 have indices 0 and 2, respectively
|
||||
graph.addEdge(0, 2);
|
||||
console.log('\nAfter adding edge 1-2, graph is');
|
||||
console.log('\nGraph after adding edge 1-2:');
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 have indices 0, 1 respectively
|
||||
/* Remove an edge */
|
||||
// Vertices 1 and 3 have indices 0 and 1, respectively
|
||||
graph.removeEdge(0, 1);
|
||||
console.log('\nAfter removing edge 1-3, graph is');
|
||||
console.log('\nGraph after removing edge 1-3:');
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
/* Add a vertex */
|
||||
graph.addVertex(6);
|
||||
console.log('\nAfter adding vertex 6, graph is');
|
||||
console.log('\nGraph after adding vertex 6:');
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
/* Remove a vertex */
|
||||
// Vertex 3 has index 1
|
||||
graph.removeVertex(1);
|
||||
console.log('\nAfter removing vertex 3, graph is');
|
||||
console.log('\nGraph after removing vertex 3:');
|
||||
graph.print();
|
||||
|
||||
@@ -8,34 +8,34 @@ const { GraphAdjList } = require('./graph_adjacency_list');
|
||||
const { Vertex } = require('../modules/Vertex');
|
||||
|
||||
/* Breadth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
function graphBFS(graph, startVet) {
|
||||
// Vertex traversal sequence
|
||||
const res = [];
|
||||
// Hash set for recording vertices that have been visited
|
||||
// Hash set recording visited vertices
|
||||
const visited = new Set();
|
||||
visited.add(startVet);
|
||||
// Queue used to implement BFS
|
||||
// Use a queue to implement BFS
|
||||
const que = [startVet];
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
// Starting from startVet, loop until all reachable vertices have been visited
|
||||
while (que.length) {
|
||||
const vet = que.shift(); // Dequeue the front vertex
|
||||
res.push(vet); // Record visited vertex
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
res.push(vet); // Record the visited vertex
|
||||
// Traverse all neighbors of this vertex
|
||||
for (const adjVet of graph.adjList.get(vet) ?? []) {
|
||||
if (visited.has(adjVet)) {
|
||||
continue; // Skip vertices that have been visited
|
||||
continue; // Skip vertices that have already been visited
|
||||
}
|
||||
que.push(adjVet); // Only enqueue unvisited vertices
|
||||
que.push(adjVet); // Enqueue only unvisited vertices
|
||||
visited.add(adjVet); // Mark this vertex as visited
|
||||
}
|
||||
}
|
||||
// Return vertex traversal sequence
|
||||
// Return the vertex traversal sequence
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
/* Driver code */
|
||||
/* Initialize the undirected graph */
|
||||
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
const edges = [
|
||||
[v[0], v[1]],
|
||||
@@ -52,10 +52,10 @@ const edges = [
|
||||
[v[7], v[8]],
|
||||
];
|
||||
const graph = new GraphAdjList(edges);
|
||||
console.log('\nAfter initialization, graph is');
|
||||
console.log('\nGraph after initialization:');
|
||||
graph.print();
|
||||
|
||||
/* Breadth-first traversal */
|
||||
const res = graphBFS(graph, v[0]);
|
||||
console.log('\nBreadth-first traversal (BFS) vertex sequence is');
|
||||
console.log('\nVertex sequence from breadth-first traversal (BFS):');
|
||||
console.log(Vertex.vetsToVals(res));
|
||||
|
||||
@@ -8,33 +8,33 @@ const { Vertex } = require('../modules/Vertex');
|
||||
const { GraphAdjList } = require('./graph_adjacency_list');
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
function dfs(graph, visited, res, vet) {
|
||||
res.push(vet); // Record visited vertex
|
||||
res.push(vet); // Record the visited vertex
|
||||
visited.add(vet); // Mark this vertex as visited
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
// Traverse all neighbors of this vertex
|
||||
for (const adjVet of graph.adjList.get(vet)) {
|
||||
if (visited.has(adjVet)) {
|
||||
continue; // Skip vertices that have been visited
|
||||
continue; // Skip vertices that have already been visited
|
||||
}
|
||||
// Recursively visit adjacent vertices
|
||||
// Recursively visit the neighboring vertex
|
||||
dfs(graph, visited, res, adjVet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
// Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
function graphDFS(graph, startVet) {
|
||||
// Vertex traversal sequence
|
||||
const res = [];
|
||||
// Hash set for recording vertices that have been visited
|
||||
// Hash set recording visited vertices
|
||||
const visited = new Set();
|
||||
dfs(graph, visited, res, startVet);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
/* Driver code */
|
||||
/* Initialize the undirected graph */
|
||||
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]);
|
||||
const edges = [
|
||||
[v[0], v[1]],
|
||||
@@ -45,10 +45,10 @@ const edges = [
|
||||
[v[5], v[6]],
|
||||
];
|
||||
const graph = new GraphAdjList(edges);
|
||||
console.log('\nAfter initialization, graph is');
|
||||
console.log('\nGraph after initialization:');
|
||||
graph.print();
|
||||
|
||||
/* Depth-first traversal */
|
||||
const res = graphDFS(graph, v[0]);
|
||||
console.log('\nDepth-first traversal (DFS) vertex sequence is');
|
||||
console.log('\nVertex sequence from depth-first traversal (DFS):');
|
||||
console.log(Vertex.vetsToVals(res));
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Greedy algorithm */
|
||||
/* Coin change: greedy algorithm */
|
||||
function coinChangeGreedy(coins, amt) {
|
||||
// Assume coins array is sorted
|
||||
// Assume coins is sorted in ascending order
|
||||
let i = coins.length - 1;
|
||||
let count = 0;
|
||||
// Loop to make greedy choices until no remaining amount
|
||||
// Repeatedly make greedy choices until no amount remains
|
||||
while (amt > 0) {
|
||||
// Find the coin that is less than and closest to the remaining amount
|
||||
// Find the largest coin no greater than the remaining amount
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
@@ -19,30 +19,30 @@ function coinChangeGreedy(coins, amt) {
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// If no feasible solution is found, return -1
|
||||
// Return -1 if no feasible solution was found
|
||||
return amt === 0 ? count : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Greedy algorithm: Can guarantee finding the global optimal solution
|
||||
/* Driver code */
|
||||
// Greedy algorithm: guaranteed to find a globally optimal solution
|
||||
let coins = [1, 5, 10, 20, 50, 100];
|
||||
let amt = 186;
|
||||
let res = coinChangeGreedy(coins, amt);
|
||||
console.log(`\ncoins = ${coins}, amt = ${amt}`);
|
||||
console.log(`Minimum coins needed to make ${amt} is ${res}`);
|
||||
console.log(`Greedy coin count for amount ${amt}: ${res}`);
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
// Greedy algorithm: not guaranteed to find a globally optimal solution
|
||||
coins = [1, 20, 50];
|
||||
amt = 60;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
console.log(`\ncoins = ${coins}, amt = ${amt}`);
|
||||
console.log(`Minimum coins needed to make ${amt} is ${res}`);
|
||||
console.log('Actually the minimum number needed is 3, i.e., 20 + 20 + 20');
|
||||
console.log(`Greedy coin count for amount ${amt}: ${res}`);
|
||||
console.log('The actual minimum is 3 coins: 20 + 20 + 20');
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
// Greedy algorithm: not guaranteed to find a globally optimal solution
|
||||
coins = [1, 49, 50];
|
||||
amt = 98;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
console.log(`\ncoins = ${coins}, amt = ${amt}`);
|
||||
console.log(`Minimum coins needed to make ${amt} is ${res}`);
|
||||
console.log('Actually the minimum number needed is 2, i.e., 49 + 49');
|
||||
console.log(`Greedy coin count for amount ${amt}: ${res}`);
|
||||
console.log('The actual minimum is 2 coins: 49 + 49');
|
||||
|
||||
@@ -12,30 +12,30 @@ class Item {
|
||||
}
|
||||
}
|
||||
|
||||
/* Fractional knapsack: Greedy algorithm */
|
||||
/* Fractional knapsack: greedy algorithm */
|
||||
function fractionalKnapsack(wgt, val, cap) {
|
||||
// Create item list with two attributes: weight, value
|
||||
// Create a list of items, each with two attributes: weight and value
|
||||
const items = wgt.map((w, i) => new Item(w, val[i]));
|
||||
// Sort by unit value item.v / item.w from high to low
|
||||
// Sort by value per unit weight, item.v / item.w, in descending order
|
||||
items.sort((a, b) => b.v / b.w - a.v / a.w);
|
||||
// Loop for greedy selection
|
||||
// Repeatedly make greedy choices
|
||||
let res = 0;
|
||||
for (const item of items) {
|
||||
if (item.w <= cap) {
|
||||
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
||||
// If enough capacity remains, put the entire current item in the knapsack
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
||||
// If the remaining capacity is insufficient, put part of the current item in the knapsack
|
||||
res += (item.v / item.w) * cap;
|
||||
// No remaining capacity, so break out of the loop
|
||||
// No capacity remains, so exit the loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const wgt = [10, 20, 30, 40, 50];
|
||||
const val = [50, 120, 150, 210, 240];
|
||||
const cap = 50;
|
||||
@@ -43,4 +43,4 @@ const n = wgt.length;
|
||||
|
||||
// Greedy algorithm
|
||||
const res = fractionalKnapsack(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
console.log(`Maximum item value within the knapsack capacity: ${res}`);
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Max capacity: Greedy algorithm */
|
||||
/* Maximum container capacity: greedy algorithm */
|
||||
function maxCapacity(ht) {
|
||||
// Initialize i, j to be at both ends of the array
|
||||
// Initialize i and j at opposite ends of the array
|
||||
let i = 0,
|
||||
j = ht.length - 1;
|
||||
// Initial max capacity is 0
|
||||
// The initial maximum capacity is 0
|
||||
let res = 0;
|
||||
// Loop for greedy selection until the two boards meet
|
||||
// Repeatedly make greedy choices until the two sides meet
|
||||
while (i < j) {
|
||||
// Update max capacity
|
||||
// Update the maximum capacity
|
||||
const cap = Math.min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.max(res, cap);
|
||||
// Move the shorter board inward
|
||||
// Move the shorter side inward
|
||||
if (ht[i] < ht[j]) {
|
||||
i += 1;
|
||||
} else {
|
||||
@@ -26,9 +26,9 @@ function maxCapacity(ht) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const ht = [3, 8, 5, 2, 7, 7, 3, 4];
|
||||
|
||||
// Greedy algorithm
|
||||
const res = maxCapacity(ht);
|
||||
console.log(`Maximum capacity is ${res}`);
|
||||
console.log(`Maximum capacity: ${res}`);
|
||||
|
||||
@@ -4,30 +4,30 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Max product cutting: Greedy algorithm */
|
||||
/* Maximum product after splitting: greedy algorithm */
|
||||
function maxProductCutting(n) {
|
||||
// When n <= 3, must cut out a 1
|
||||
// When n <= 3, one part must be 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// Greedily cut out 3, a is the number of 3s, b is the remainder
|
||||
// Greedily split off parts of size 3; a is the number of 3s and b is the remainder
|
||||
let a = Math.floor(n / 3);
|
||||
let b = n % 3;
|
||||
if (b === 1) {
|
||||
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
|
||||
// When the remainder is 1, replace one pair 1 * 3 with 2 * 2
|
||||
return Math.pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b === 2) {
|
||||
// When the remainder is 2, do nothing
|
||||
// When the remainder is 2, no adjustment is needed
|
||||
return Math.pow(3, a) * 2;
|
||||
}
|
||||
// When the remainder is 0, do nothing
|
||||
// When the remainder is 0, no adjustment is needed
|
||||
return Math.pow(3, a);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
let n = 58;
|
||||
|
||||
// Greedy algorithm
|
||||
let res = maxProductCutting(n);
|
||||
console.log(`Maximum cutting product is ${res}`);
|
||||
console.log(`Maximum product after splitting: ${res}`);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair Number -> String */
|
||||
/* Key-value pair: Number -> String */
|
||||
class Pair {
|
||||
constructor(key, val) {
|
||||
this.key = key;
|
||||
@@ -12,11 +12,11 @@ class Pair {
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash table based on array implementation */
|
||||
/* Hash table implemented with an array */
|
||||
class ArrayHashMap {
|
||||
#buckets;
|
||||
constructor() {
|
||||
// Initialize array with 100 buckets
|
||||
// Initialize an array containing 100 buckets
|
||||
this.#buckets = new Array(100).fill(null);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ class ArrayHashMap {
|
||||
return key % 100;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
/* Lookup operation */
|
||||
get(key) {
|
||||
let index = this.#hashFunc(key);
|
||||
let pair = this.#buckets[index];
|
||||
@@ -33,7 +33,7 @@ class ArrayHashMap {
|
||||
return pair.val;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
/* Insert operation */
|
||||
set(key, val) {
|
||||
let index = this.#hashFunc(key);
|
||||
this.#buckets[index] = new Pair(key, val);
|
||||
@@ -42,7 +42,7 @@ class ArrayHashMap {
|
||||
/* Remove operation */
|
||||
delete(key) {
|
||||
let index = this.#hashFunc(key);
|
||||
// Set to null to represent deletion
|
||||
// Set the bucket to null to mark it as deleted
|
||||
this.#buckets[index] = null;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ class ArrayHashMap {
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
/* Print the hash table */
|
||||
print() {
|
||||
let pairSet = this.entries();
|
||||
for (const pair of pairSet) {
|
||||
@@ -88,41 +88,41 @@ class ArrayHashMap {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize hash table */
|
||||
/* Driver code */
|
||||
/* Initialize the hash table */
|
||||
const map = new ArrayHashMap();
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.set(12836, 'Xiao Ha');
|
||||
map.set(15937, 'Xiao Luo');
|
||||
map.set(16750, 'Xiao Suan');
|
||||
map.set(13276, 'Xiao Fa');
|
||||
map.set(10583, 'Xiao Ya');
|
||||
console.info('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
map.set(12836, '小哈');
|
||||
map.set(15937, '小啰');
|
||||
map.set(16750, '小算');
|
||||
map.set(13276, '小法');
|
||||
map.set(10583, '小鸭');
|
||||
console.info('\nHash table after insertion:\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
let name = map.get(15937);
|
||||
console.info('\nInput student ID 15937, query name ' + name);
|
||||
console.info('\nLook up student ID 15937 to obtain the name ' + name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
map.delete(10583);
|
||||
console.info('\nAfter removing 10583, hash table is\nKey -> Value');
|
||||
console.info('\nHash table after removing 10583:\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
/* Traverse hash table */
|
||||
console.info('\nTraverse key-value pairs Key->Value');
|
||||
/* Traverse the hash table */
|
||||
console.info('\nTraverse key-value pairs: Key->Value');
|
||||
for (const pair of map.entries()) {
|
||||
if (!pair) continue;
|
||||
console.info(pair.key + ' -> ' + pair.val);
|
||||
}
|
||||
console.info('\nTraverse keys only Key');
|
||||
console.info('\nTraverse keys only: Key');
|
||||
for (const key of map.keys()) {
|
||||
console.info(key);
|
||||
}
|
||||
console.info('\nTraverse values only Value');
|
||||
console.info('\nTraverse values only: Value');
|
||||
for (const val of map.values()) {
|
||||
console.info(val);
|
||||
}
|
||||
|
||||
@@ -4,41 +4,41 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize hash table */
|
||||
/* Driver code */
|
||||
/* Initialize the hash table */
|
||||
const map = new Map();
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.set(12836, 'Xiao Ha');
|
||||
map.set(15937, 'Xiao Luo');
|
||||
map.set(16750, 'Xiao Suan');
|
||||
map.set(13276, 'Xiao Fa');
|
||||
map.set(10583, 'Xiao Ya');
|
||||
console.info('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
map.set(12836, '小哈');
|
||||
map.set(15937, '小啰');
|
||||
map.set(16750, '小算');
|
||||
map.set(13276, '小法');
|
||||
map.set(10583, '小鸭');
|
||||
console.info('\nHash table after insertion:\nKey -> Value');
|
||||
console.info(map);
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
let name = map.get(15937);
|
||||
console.info('\nInput student ID 15937, query name ' + name);
|
||||
console.info('\nLook up student ID 15937 to obtain the name ' + name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
map.delete(10583);
|
||||
console.info('\nAfter removing 10583, hash table is\nKey -> Value');
|
||||
console.info('\nHash table after removing 10583:\nKey -> Value');
|
||||
console.info(map);
|
||||
|
||||
/* Traverse hash table */
|
||||
console.info('\nTraverse key-value pairs Key->Value');
|
||||
/* Traverse the hash table */
|
||||
console.info('\nTraverse key-value pairs: Key->Value');
|
||||
for (const [k, v] of map.entries()) {
|
||||
console.info(k + ' -> ' + v);
|
||||
}
|
||||
console.info('\nTraverse keys only Key');
|
||||
console.info('\nTraverse keys only: Key');
|
||||
for (const k of map.keys()) {
|
||||
console.info(k);
|
||||
}
|
||||
console.info('\nTraverse values only Value');
|
||||
console.info('\nTraverse values only: Value');
|
||||
for (const v of map.values()) {
|
||||
console.info(v);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair Number -> String */
|
||||
/* Key-value pair: Number -> String */
|
||||
class Pair {
|
||||
constructor(key, val) {
|
||||
this.key = key;
|
||||
@@ -16,8 +16,8 @@ class Pair {
|
||||
class HashMapChaining {
|
||||
#size; // Number of key-value pairs
|
||||
#capacity; // Hash table capacity
|
||||
#loadThres; // Load factor threshold for triggering expansion
|
||||
#extendRatio; // Expansion multiplier
|
||||
#loadThres; // Load factor threshold that triggers capacity growth
|
||||
#extendRatio; // Capacity growth factor
|
||||
#buckets; // Bucket array
|
||||
|
||||
/* Constructor */
|
||||
@@ -39,36 +39,36 @@ class HashMapChaining {
|
||||
return this.#size / this.#capacity;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
/* Lookup operation */
|
||||
get(key) {
|
||||
const index = this.#hashFunc(key);
|
||||
const bucket = this.#buckets[index];
|
||||
// Traverse bucket, if key is found, return corresponding val
|
||||
// Traverse the bucket; if key is found, return its corresponding val
|
||||
for (const pair of bucket) {
|
||||
if (pair.key === key) {
|
||||
return pair.val;
|
||||
}
|
||||
}
|
||||
// If key is not found, return null
|
||||
// Return null if key was not found
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
/* Insert operation */
|
||||
put(key, val) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
// Grow the capacity when the load factor exceeds the threshold
|
||||
if (this.#loadFactor() > this.#loadThres) {
|
||||
this.#extend();
|
||||
}
|
||||
const index = this.#hashFunc(key);
|
||||
const bucket = this.#buckets[index];
|
||||
// Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
// Traverse the bucket; if the specified key is found, update its val and return
|
||||
for (const pair of bucket) {
|
||||
if (pair.key === key) {
|
||||
pair.val = val;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// If key does not exist, append key-value pair to the end
|
||||
// If key is absent, append the key-value pair at the end
|
||||
const pair = new Pair(key, val);
|
||||
bucket.push(pair);
|
||||
this.#size++;
|
||||
@@ -78,7 +78,7 @@ class HashMapChaining {
|
||||
remove(key) {
|
||||
const index = this.#hashFunc(key);
|
||||
let bucket = this.#buckets[index];
|
||||
// Traverse bucket and remove key-value pair from it
|
||||
// Traverse the bucket and remove the key-value pair
|
||||
for (let i = 0; i < bucket.length; i++) {
|
||||
if (bucket[i].key === key) {
|
||||
bucket.splice(i, 1);
|
||||
@@ -88,15 +88,15 @@ class HashMapChaining {
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
/* Grow the hash table capacity */
|
||||
#extend() {
|
||||
// Temporarily store the original hash table
|
||||
// Keep a reference to the original hash table
|
||||
const bucketsTmp = this.#buckets;
|
||||
// Initialize expanded new hash table
|
||||
// Initialize a new hash table with the expanded capacity
|
||||
this.#capacity *= this.#extendRatio;
|
||||
this.#buckets = new Array(this.#capacity).fill(null).map((x) => []);
|
||||
this.#size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
// Move the key-value pairs from the original hash table to the new one
|
||||
for (const bucket of bucketsTmp) {
|
||||
for (const pair of bucket) {
|
||||
this.put(pair.key, pair.val);
|
||||
@@ -104,7 +104,7 @@ class HashMapChaining {
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
/* Print the hash table */
|
||||
print() {
|
||||
for (const bucket of this.#buckets) {
|
||||
let res = [];
|
||||
@@ -116,27 +116,27 @@ class HashMapChaining {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize hash table */
|
||||
/* Driver code */
|
||||
/* Initialize the hash table */
|
||||
const map = new HashMapChaining();
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.put(12836, 'Xiao Ha');
|
||||
map.put(15937, 'Xiao Luo');
|
||||
map.put(16750, 'Xiao Suan');
|
||||
map.put(13276, 'Xiao Fa');
|
||||
map.put(10583, 'Xiao Ya');
|
||||
console.log('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
/* Insert operation */
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
map.put(12836, '小哈');
|
||||
map.put(15937, '小啰');
|
||||
map.put(16750, '小算');
|
||||
map.put(13276, '小法');
|
||||
map.put(10583, '小鸭');
|
||||
console.log('\nHash table after insertion:\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
/* Lookup operation */
|
||||
// Look up key in the hash table to obtain value
|
||||
const name = map.get(13276);
|
||||
console.log('\nInput student ID 13276, query name ' + name);
|
||||
console.log('\nLook up student ID 13276 to obtain the name ' + name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
map.remove(12836);
|
||||
console.log('\nAfter removing 12836, hash table is\nKey -> Value');
|
||||
console.log('\nHash table after removing 12836:\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: yuan0221 (yl1452491917@gmail.com), krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair Number -> String */
|
||||
/* Key-value pair: Number -> String */
|
||||
class Pair {
|
||||
constructor(key, val) {
|
||||
this.key = key;
|
||||
@@ -16,19 +16,19 @@ class Pair {
|
||||
class HashMapOpenAddressing {
|
||||
#size; // Number of key-value pairs
|
||||
#capacity; // Hash table capacity
|
||||
#loadThres; // Load factor threshold for triggering expansion
|
||||
#extendRatio; // Expansion multiplier
|
||||
#loadThres; // Load factor threshold that triggers capacity growth
|
||||
#extendRatio; // Capacity growth factor
|
||||
#buckets; // Bucket array
|
||||
#TOMBSTONE; // Removal marker
|
||||
#TOMBSTONE; // Tombstone marker
|
||||
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
this.#size = 0; // Number of key-value pairs
|
||||
this.#capacity = 4; // Hash table capacity
|
||||
this.#loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
|
||||
this.#extendRatio = 2; // Expansion multiplier
|
||||
this.#loadThres = 2.0 / 3.0; // Load factor threshold that triggers capacity growth
|
||||
this.#extendRatio = 2; // Capacity growth factor
|
||||
this.#buckets = Array(this.#capacity).fill(null); // Bucket array
|
||||
this.#TOMBSTONE = new Pair(-1, '-1'); // Removal marker
|
||||
this.#TOMBSTONE = new Pair(-1, '-1'); // Tombstone marker
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
@@ -41,60 +41,60 @@ class HashMapOpenAddressing {
|
||||
return this.#size / this.#capacity;
|
||||
}
|
||||
|
||||
/* Search for bucket index corresponding to key */
|
||||
/* Find the bucket index for key */
|
||||
#findBucket(key) {
|
||||
let index = this.#hashFunc(key);
|
||||
let firstTombstone = -1;
|
||||
// Linear probing, break when encountering an empty bucket
|
||||
// Probe linearly until an empty bucket is reached
|
||||
while (this.#buckets[index] !== null) {
|
||||
// If key is encountered, return the corresponding bucket index
|
||||
// If key is found, return its bucket index
|
||||
if (this.#buckets[index].key === key) {
|
||||
// If a removal marker was encountered before, move the key-value pair to that index
|
||||
// If a tombstone was encountered earlier, move the key-value pair to that index
|
||||
if (firstTombstone !== -1) {
|
||||
this.#buckets[firstTombstone] = this.#buckets[index];
|
||||
this.#buckets[index] = this.#TOMBSTONE;
|
||||
return firstTombstone; // Return the moved bucket index
|
||||
return firstTombstone; // Return the bucket index after the move
|
||||
}
|
||||
return index; // Return bucket index
|
||||
return index; // Return the bucket index
|
||||
}
|
||||
// Record the first removal marker encountered
|
||||
// Record the first tombstone encountered
|
||||
if (
|
||||
firstTombstone === -1 &&
|
||||
this.#buckets[index] === this.#TOMBSTONE
|
||||
) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// Calculate bucket index, wrap around to the head if past the tail
|
||||
// Calculate the bucket index, wrapping to the beginning after the end
|
||||
index = (index + 1) % this.#capacity;
|
||||
}
|
||||
// If key does not exist, return the index for insertion
|
||||
// If key is absent, return the index for insertion
|
||||
return firstTombstone === -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
/* Lookup operation */
|
||||
get(key) {
|
||||
// Search for bucket index corresponding to key
|
||||
// Find the bucket index for key
|
||||
const index = this.#findBucket(key);
|
||||
// If key-value pair is found, return corresponding val
|
||||
// If the key-value pair is found, return its val
|
||||
if (
|
||||
this.#buckets[index] !== null &&
|
||||
this.#buckets[index] !== this.#TOMBSTONE
|
||||
) {
|
||||
return this.#buckets[index].val;
|
||||
}
|
||||
// If key-value pair does not exist, return null
|
||||
// Return null if the key-value pair does not exist
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
/* Insert operation */
|
||||
put(key, val) {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
// Grow the capacity when the load factor exceeds the threshold
|
||||
if (this.#loadFactor() > this.#loadThres) {
|
||||
this.#extend();
|
||||
}
|
||||
// Search for bucket index corresponding to key
|
||||
// Find the bucket index for key
|
||||
const index = this.#findBucket(key);
|
||||
// If key-value pair is found, overwrite val and return
|
||||
// If the key-value pair is found, overwrite val and return
|
||||
if (
|
||||
this.#buckets[index] !== null &&
|
||||
this.#buckets[index] !== this.#TOMBSTONE
|
||||
@@ -102,16 +102,16 @@ class HashMapOpenAddressing {
|
||||
this.#buckets[index].val = val;
|
||||
return;
|
||||
}
|
||||
// If key-value pair does not exist, add the key-value pair
|
||||
// If the key-value pair is absent, insert it
|
||||
this.#buckets[index] = new Pair(key, val);
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
remove(key) {
|
||||
// Search for bucket index corresponding to key
|
||||
// Find the bucket index for key
|
||||
const index = this.#findBucket(key);
|
||||
// If key-value pair is found, overwrite it with removal marker
|
||||
// If the key-value pair is found, replace it with a tombstone
|
||||
if (
|
||||
this.#buckets[index] !== null &&
|
||||
this.#buckets[index] !== this.#TOMBSTONE
|
||||
@@ -121,15 +121,15 @@ class HashMapOpenAddressing {
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
/* Grow the hash table capacity */
|
||||
#extend() {
|
||||
// Temporarily store the original hash table
|
||||
// Keep a reference to the original hash table
|
||||
const bucketsTmp = this.#buckets;
|
||||
// Initialize expanded new hash table
|
||||
// Initialize a new hash table with the expanded capacity
|
||||
this.#capacity *= this.#extendRatio;
|
||||
this.#buckets = Array(this.#capacity).fill(null);
|
||||
this.#size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
// Move the key-value pairs from the original hash table to the new one
|
||||
for (const pair of bucketsTmp) {
|
||||
if (pair !== null && pair !== this.#TOMBSTONE) {
|
||||
this.put(pair.key, pair.val);
|
||||
@@ -137,7 +137,7 @@ class HashMapOpenAddressing {
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
/* Print the hash table */
|
||||
print() {
|
||||
for (const pair of this.#buckets) {
|
||||
if (pair === null) {
|
||||
@@ -151,27 +151,27 @@ class HashMapOpenAddressing {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Initialize hash table
|
||||
/* Driver code */
|
||||
// Initialize the hash table
|
||||
const hashmap = new HashMapOpenAddressing();
|
||||
|
||||
// Add operation
|
||||
// Add key-value pair (key, val) to the hash table
|
||||
hashmap.put(12836, 'Xiao Ha');
|
||||
hashmap.put(15937, 'Xiao Luo');
|
||||
hashmap.put(16750, 'Xiao Suan');
|
||||
hashmap.put(13276, 'Xiao Fa');
|
||||
hashmap.put(10583, 'Xiao Ya');
|
||||
console.log('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
// Insert operation
|
||||
// Insert the key-value pair (key, val) into the hash table
|
||||
hashmap.put(12836, '小哈');
|
||||
hashmap.put(15937, '小啰');
|
||||
hashmap.put(16750, '小算');
|
||||
hashmap.put(13276, '小法');
|
||||
hashmap.put(10583, '小鸭');
|
||||
console.log('\nHash table after insertion:\nKey -> Value');
|
||||
hashmap.print();
|
||||
|
||||
// Query operation
|
||||
// Input key into hash table to get value val
|
||||
// Lookup operation
|
||||
// Look up key in the hash table to obtain val
|
||||
const name = hashmap.get(13276);
|
||||
console.log('\nInput student ID 13276, query name ' + name);
|
||||
console.log('\nLook up student ID 13276 to obtain the name ' + name);
|
||||
|
||||
// Remove operation
|
||||
// Remove key-value pair (key, val) from hash table
|
||||
// Remove the key-value pair (key, val) from the hash table
|
||||
hashmap.remove(16750);
|
||||
console.log('\nAfter removing 16750, hash table is\nKey -> Value');
|
||||
console.log('\nHash table after removing 16750:\nKey -> Value');
|
||||
hashmap.print();
|
||||
|
||||
@@ -34,7 +34,7 @@ function xorHash(key) {
|
||||
return hash % MODULUS;
|
||||
}
|
||||
|
||||
/* Rotational hash */
|
||||
/* Rotating hash */
|
||||
function rotHash(key) {
|
||||
let hash = 0;
|
||||
const MODULUS = 1000000007;
|
||||
@@ -44,17 +44,17 @@ function rotHash(key) {
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const key = 'Hello Algo';
|
||||
/* Driver code */
|
||||
const key = 'Hello 算法';
|
||||
|
||||
let hash = addHash(key);
|
||||
console.log('Additive hash value is ' + hash);
|
||||
console.log('Additive hash value: ' + hash);
|
||||
|
||||
hash = mulHash(key);
|
||||
console.log('Multiplicative hash value is ' + hash);
|
||||
console.log('Multiplicative hash value: ' + hash);
|
||||
|
||||
hash = xorHash(key);
|
||||
console.log('XOR hash value is ' + hash);
|
||||
console.log('XOR hash value: ' + hash);
|
||||
|
||||
hash = rotHash(key);
|
||||
console.log('Rotational hash value is ' + hash);
|
||||
console.log('Rotating hash value: ' + hash);
|
||||
|
||||
@@ -10,27 +10,27 @@ const { printHeap } = require('../modules/PrintUtil');
|
||||
class MaxHeap {
|
||||
#maxHeap;
|
||||
|
||||
/* Constructor, build empty heap or build heap from input list */
|
||||
/* Constructor: create an empty heap or build a heap from the input list */
|
||||
constructor(nums) {
|
||||
// Add list elements to heap as is
|
||||
// Place the list elements in the heap without changing their order
|
||||
this.#maxHeap = nums === undefined ? [] : [...nums];
|
||||
// Heapify all nodes except leaf nodes
|
||||
// Sift down from every non-leaf node
|
||||
for (let i = this.#parent(this.size() - 1); i >= 0; i--) {
|
||||
this.#siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
/* Get the left child index */
|
||||
#left(i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
/* Get the right child index */
|
||||
#right(i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
/* Get the parent index */
|
||||
#parent(i) {
|
||||
return Math.floor((i - 1) / 2); // Floor division
|
||||
}
|
||||
@@ -42,115 +42,115 @@ class MaxHeap {
|
||||
this.#maxHeap[j] = tmp;
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
size() {
|
||||
return this.#maxHeap.length;
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
isEmpty() {
|
||||
return this.size() === 0;
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
/* Access the top element of the heap */
|
||||
peek() {
|
||||
return this.#maxHeap[0];
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
push(val) {
|
||||
// Add node
|
||||
// Add a node
|
||||
this.#maxHeap.push(val);
|
||||
// Heapify from bottom to top
|
||||
// Sift up
|
||||
this.#siftUp(this.size() - 1);
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
/* Sift up starting from node i */
|
||||
#siftUp(i) {
|
||||
while (true) {
|
||||
// Get parent node of node i
|
||||
// Get the parent of node i
|
||||
const p = this.#parent(i);
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
// Stop sifting when the root has been passed or the node needs no repair
|
||||
if (p < 0 || this.#maxHeap[i] <= this.#maxHeap[p]) break;
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
this.#swap(i, p);
|
||||
// Loop upward heapify
|
||||
// Continue sifting up
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
/* Pop an element from the heap */
|
||||
pop() {
|
||||
// Handle empty case
|
||||
// Handle an empty heap
|
||||
if (this.isEmpty()) throw new Error('Heap is empty');
|
||||
// Delete node
|
||||
// Swap the root with the rightmost leaf on the last level (swap the first and last elements)
|
||||
this.#swap(0, this.size() - 1);
|
||||
// Remove node
|
||||
// Remove a node
|
||||
const val = this.#maxHeap.pop();
|
||||
// Return top element
|
||||
// Sift down
|
||||
this.#siftDown(0);
|
||||
// Return heap top element
|
||||
// Return the top element of the heap
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
/* Sift down starting from node i */
|
||||
#siftDown(i) {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
const l = this.#left(i),
|
||||
r = this.#right(i);
|
||||
let ma = i;
|
||||
if (l < this.size() && this.#maxHeap[l] > this.#maxHeap[ma]) ma = l;
|
||||
if (r < this.size() && this.#maxHeap[r] > this.#maxHeap[ma]) ma = r;
|
||||
// Swap two nodes
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma === i) break;
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
this.#swap(i, ma);
|
||||
// Loop downwards heapification
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Print the heap (binary tree) */
|
||||
print() {
|
||||
printHeap(this.#maxHeap);
|
||||
}
|
||||
|
||||
/* Extract elements from heap */
|
||||
/* Get the elements in the heap */
|
||||
getMaxHeap() {
|
||||
return this.#maxHeap;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
if (require.main === module) {
|
||||
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
|
||||
/* Initialize a max heap */
|
||||
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
||||
console.log('\nAfter inputting list and building heap');
|
||||
console.log('\nAfter building a heap from the input list:');
|
||||
maxHeap.print();
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Get the top element of the heap */
|
||||
let peek = maxHeap.peek();
|
||||
console.log(`\nHeap top element is ${peek}`);
|
||||
console.log(`\nHeap top: ${peek}`);
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
let val = 7;
|
||||
maxHeap.push(val);
|
||||
console.log(`\nAfter element ${val} pushes to heap`);
|
||||
console.log(`\nAfter pushing ${val} into the heap:`);
|
||||
maxHeap.print();
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
/* Pop the top element from the heap */
|
||||
peek = maxHeap.pop();
|
||||
console.log(`\nAfter heap top element ${peek} pops from heap`);
|
||||
console.log(`\nAfter popping the heap top ${peek}:`);
|
||||
maxHeap.print();
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
let size = maxHeap.size();
|
||||
console.log(`\nHeap size is ${size}`);
|
||||
console.log(`\nNumber of elements in the heap: ${size}`);
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
let isEmpty = maxHeap.isEmpty();
|
||||
console.log(`\nIs heap empty ${isEmpty}`);
|
||||
console.log(`\nIs the heap empty? ${isEmpty}`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -6,52 +6,52 @@
|
||||
|
||||
const { MaxHeap } = require('./my_heap');
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
function pushMinHeap(maxHeap, val) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
maxHeap.push(-val);
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
/* Pop an element from the heap */
|
||||
function popMinHeap(maxHeap) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
return -maxHeap.pop();
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
/* Access the top element of the heap */
|
||||
function peekMinHeap(maxHeap) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
return -maxHeap.peek();
|
||||
}
|
||||
|
||||
/* Extract elements from heap */
|
||||
/* Get the elements in the heap */
|
||||
function getMinHeap(maxHeap) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
return maxHeap.getMaxHeap().map((num) => -num);
|
||||
}
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
/* Use a heap to find the k largest elements in an array */
|
||||
function topKHeap(nums, k) {
|
||||
// Python's heapq module implements min heap by default
|
||||
// Note: We negate all heap elements to simulate min heap using max heap
|
||||
// Initialize a min heap
|
||||
// Note: negate all values in the heap to simulate a min heap with a max heap
|
||||
const maxHeap = new MaxHeap([]);
|
||||
// Enter the first k elements of array into heap
|
||||
// Push the first k array elements onto the heap
|
||||
for (let i = 0; i < k; i++) {
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
// Starting with element k+1, keep the heap size at k
|
||||
for (let i = k; i < nums.length; i++) {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
// If the current element is larger than the heap top, pop the top element and push the current element
|
||||
if (nums[i] > peekMinHeap(maxHeap)) {
|
||||
popMinHeap(maxHeap);
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
}
|
||||
// Return elements in heap
|
||||
// Return the elements in the heap
|
||||
return getMinHeap(maxHeap);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [1, 7, 6, 3, 2];
|
||||
const k = 3;
|
||||
const res = topKHeap(nums, k);
|
||||
|
||||
@@ -4,57 +4,57 @@
|
||||
* Author: JoseHung (szhong@link.cuhk.edu.hk)
|
||||
*/
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
/* Binary search (closed interval) */
|
||||
function binarySearch(nums, target) {
|
||||
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
|
||||
// Initialize the closed interval [0, n-1], with i and j pointing to the first and last elements
|
||||
let i = 0,
|
||||
j = nums.length - 1;
|
||||
// Loop, exit when the search interval is empty (empty when i > j)
|
||||
// Loop until the search interval is empty (when i > j)
|
||||
while (i <= j) {
|
||||
// Calculate midpoint index m, use parseInt() to round down
|
||||
// Calculate midpoint index m, using parseInt() to round down
|
||||
const m = parseInt(i + (j - i) / 2);
|
||||
if (nums[m] < target)
|
||||
// This means target is in the interval [m+1, j]
|
||||
// In this case, target must be in [m+1, j] if it exists
|
||||
i = m + 1;
|
||||
else if (nums[m] > target)
|
||||
// This means target is in the interval [i, m-1]
|
||||
// In this case, target must be in [i, m-1] if it exists
|
||||
j = m - 1;
|
||||
else return m; // Found the target element, return its index
|
||||
else return m; // The target element was found; return its index
|
||||
}
|
||||
// Target element not found, return -1
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
/* Binary search (left-closed, right-open interval) */
|
||||
function binarySearchLCRO(nums, target) {
|
||||
// Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
|
||||
// Initialize the left-closed, right-open interval [0, n), with i at the first element and j one past the last
|
||||
let i = 0,
|
||||
j = nums.length;
|
||||
// Loop, exit when the search interval is empty (empty when i = j)
|
||||
// Loop until the search interval is empty (when i = j)
|
||||
while (i < j) {
|
||||
// Calculate midpoint index m, use parseInt() to round down
|
||||
// Calculate midpoint index m, using parseInt() to round down
|
||||
const m = parseInt(i + (j - i) / 2);
|
||||
if (nums[m] < target)
|
||||
// This means target is in the interval [m+1, j)
|
||||
// In this case, target must be in [m+1, j) if it exists
|
||||
i = m + 1;
|
||||
else if (nums[m] > target)
|
||||
// This means target is in the interval [i, m)
|
||||
// In this case, target must be in [i, m) if it exists
|
||||
j = m;
|
||||
// Found the target element, return its index
|
||||
// The target element was found; return its index
|
||||
else return m;
|
||||
}
|
||||
// Target element not found, return -1
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const target = 6;
|
||||
const nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
/* Binary search (closed interval) */
|
||||
let index = binarySearch(nums, target);
|
||||
console.log('Index of target element 6 = ' + index);
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
/* Binary search (left-closed, right-open interval) */
|
||||
index = binarySearchLCRO(nums, target);
|
||||
console.log('Index of target element 6 = ' + index);
|
||||
|
||||
@@ -6,40 +6,40 @@
|
||||
|
||||
const { binarySearchInsertion } = require('./binary_search_insertion.js');
|
||||
|
||||
/* Binary search for the leftmost target */
|
||||
/* Find the leftmost occurrence of target using binary search */
|
||||
function binarySearchLeftEdge(nums, target) {
|
||||
// Equivalent to finding the insertion point of target
|
||||
// This is equivalent to finding the insertion point of target
|
||||
const i = binarySearchInsertion(nums, target);
|
||||
// Target not found, return -1
|
||||
// If target was not found, return -1
|
||||
if (i === nums.length || nums[i] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index i
|
||||
// Target was found; return index i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
/* Find the rightmost occurrence of target using binary search */
|
||||
function binarySearchRightEdge(nums, target) {
|
||||
// Convert to finding the leftmost target + 1
|
||||
// Reduce the problem to finding the leftmost insertion point of target + 1
|
||||
const i = binarySearchInsertion(nums, target + 1);
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
// j points to the rightmost target, while i points to the first element greater than target
|
||||
const j = i - 1;
|
||||
// Target not found, return -1
|
||||
// If target was not found, return -1
|
||||
if (j === -1 || nums[j] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index j
|
||||
// Target was found; return index j
|
||||
return j;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Array with duplicate elements
|
||||
/* Driver code */
|
||||
// Array containing duplicate elements
|
||||
const nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
console.log('\nArray nums = ' + nums);
|
||||
// Binary search left and right boundaries
|
||||
// Find the left and right boundaries using binary search
|
||||
for (const target of [6, 7]) {
|
||||
let index = binarySearchLeftEdge(nums, target);
|
||||
console.log('Leftmost element ' + target + ' has index ' + index);
|
||||
console.log('Leftmost occurrence of ' + target + ' has index ' + index);
|
||||
index = binarySearchRightEdge(nums, target);
|
||||
console.log('Rightmost element ' + target + ' has index ' + index);
|
||||
console.log('Rightmost occurrence of ' + target + ' has index ' + index);
|
||||
}
|
||||
|
||||
@@ -4,59 +4,59 @@
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
/* Find an insertion point using binary search (no duplicates) */
|
||||
function binarySearchInsertionSimple(nums, target) {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // Initialize closed interval [0, n-1]
|
||||
j = nums.length - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, use Math.floor() to round down
|
||||
const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, using Math.floor() to round down
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
j = m - 1; // Target must be in [i, m-1] if it exists
|
||||
} else {
|
||||
return m; // Found target, return insertion point m
|
||||
return m; // Target was found; return insertion point m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
// Target was not found; return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
/* Find an insertion point using binary search (with duplicates) */
|
||||
function binarySearchInsertion(nums, target) {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // Initialize closed interval [0, n-1]
|
||||
j = nums.length - 1; // Initialize the closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, use Math.floor() to round down
|
||||
const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, using Math.floor() to round down
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
i = m + 1; // Target must be in [m+1, j] if it exists
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
j = m - 1; // Target must be in [i, m-1] if it exists
|
||||
} else {
|
||||
j = m - 1; // The rightmost element less than target is in the interval [i, m-1]
|
||||
j = m - 1; // Continue in [i, m-1] to find the rightmost element smaller than target
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Array without duplicate elements
|
||||
/* Driver code */
|
||||
// Array with no duplicate elements
|
||||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
console.log('\nArray nums = ' + nums);
|
||||
// Binary search for insertion point
|
||||
// Find an insertion point using binary search
|
||||
for (const target of [6, 9]) {
|
||||
const index = binarySearchInsertionSimple(nums, target);
|
||||
console.log('Element ' + target + "'s insertion point index is " + index);
|
||||
console.log('Element ' + target + ' has insertion index ' + index);
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
// Array containing duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
console.log('\nArray nums = ' + nums);
|
||||
// Binary search for insertion point
|
||||
// Find an insertion point using binary search
|
||||
for (const target of [2, 6, 20]) {
|
||||
const index = binarySearchInsertion(nums, target);
|
||||
console.log('Element ' + target + "'s insertion point index is " + index);
|
||||
console.log('Element ' + target + ' has insertion index ' + index);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -6,40 +6,40 @@
|
||||
|
||||
const { arrToLinkedList } = require('../modules/ListNode');
|
||||
|
||||
/* Hash search (array) */
|
||||
/* Hash-based search (array) */
|
||||
function hashingSearchArray(map, target) {
|
||||
// Hash table's key: target element, value: index
|
||||
// If this key does not exist in the hash table, return -1
|
||||
// Hash table key: target element; value: index
|
||||
// Return -1 if the hash table does not contain this key
|
||||
return map.has(target) ? map.get(target) : -1;
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
/* Hash-based search (linked list) */
|
||||
function hashingSearchLinkedList(map, target) {
|
||||
// Hash table key: target node value, value: node object
|
||||
// If key is not in hash table, return null
|
||||
// Hash table key: target node value; value: node object
|
||||
// Return null if this key is absent from the hash table
|
||||
return map.has(target) ? map.get(target) : null;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const target = 3;
|
||||
|
||||
/* Hash search (array) */
|
||||
/* Hash-based search (array) */
|
||||
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
const map = new Map();
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
map.set(nums[i], i); // key: element, value: index
|
||||
map.set(nums[i], i); // key: element; value: index
|
||||
}
|
||||
const index = hashingSearchArray(map, target);
|
||||
console.log('Index of target element 3 = ' + index);
|
||||
|
||||
/* Hash search (linked list) */
|
||||
/* Hash-based search (linked list) */
|
||||
let head = arrToLinkedList(nums);
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
const map1 = new Map();
|
||||
while (head != null) {
|
||||
map1.set(head.val, head); // key: node value, value: node
|
||||
map1.set(head.val, head); // key: node value; value: node
|
||||
head = head.next;
|
||||
}
|
||||
const node = hashingSearchLinkedList(map1, target);
|
||||
console.log('Node object with target value 3 is', node);
|
||||
console.log('The node object corresponding to target value 3 is', node);
|
||||
|
||||
@@ -8,40 +8,40 @@ const { ListNode, arrToLinkedList } = require('../modules/ListNode');
|
||||
|
||||
/* Linear search (array) */
|
||||
function linearSearchArray(nums, target) {
|
||||
// Traverse array
|
||||
// Traverse the array
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
// Found the target element, return its index
|
||||
// The target element was found; return its index
|
||||
if (nums[i] === target) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Linear search (linked list) */
|
||||
/* Linear search (linked list)*/
|
||||
function linearSearchLinkedList(head, target) {
|
||||
// Traverse the linked list
|
||||
while (head) {
|
||||
// Found the target node, return it
|
||||
// The target node was found; return it
|
||||
if (head.val === target) {
|
||||
return head;
|
||||
}
|
||||
head = head.next;
|
||||
}
|
||||
// Target node not found, return null
|
||||
// Target node not found; return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const target = 3;
|
||||
|
||||
/* Perform linear search in array */
|
||||
/* Perform linear search on the array */
|
||||
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
const index = linearSearchArray(nums, target);
|
||||
console.log('Index of target element 3 = ' + index);
|
||||
|
||||
/* Perform linear search in linked list */
|
||||
/* Perform linear search on the linked list */
|
||||
const head = arrToLinkedList(nums);
|
||||
const node = linearSearchLinkedList(head, target);
|
||||
console.log('Node object corresponding to target node value 3 is ', node);
|
||||
console.log('The node object corresponding to target value 3 is ', node);
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
* Author: gyt95 (gytkwan@gmail.com)
|
||||
*/
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
/* Method 1: brute-force enumeration */
|
||||
function twoSumBruteForce(nums, target) {
|
||||
const n = nums.length;
|
||||
// Two nested loops, time complexity is O(n^2)
|
||||
// Two nested loops give a time complexity of O(n^2)
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[i] + nums[j] === target) {
|
||||
@@ -18,11 +18,11 @@ function twoSumBruteForce(nums, target) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/* Method 2: Auxiliary hash table */
|
||||
/* Method 2: auxiliary hash table */
|
||||
function twoSumHashTable(nums, target) {
|
||||
// Auxiliary hash table, space complexity is O(n)
|
||||
// The auxiliary hash table uses O(n) space
|
||||
let m = {};
|
||||
// Single loop, time complexity is O(n)
|
||||
// A single loop gives a time complexity of O(n)
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (m[target - nums[i]] !== undefined) {
|
||||
return [m[target - nums[i]], i];
|
||||
@@ -33,14 +33,14 @@ function twoSumHashTable(nums, target) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
// Method 1
|
||||
const nums = [2, 7, 11, 15],
|
||||
target = 13;
|
||||
|
||||
let res = twoSumBruteForce(nums, target);
|
||||
console.log('Method 1 res = ', res);
|
||||
console.log('Method 1: res = ', res);
|
||||
|
||||
// Method 2
|
||||
res = twoSumHashTable(nums, target);
|
||||
console.log('Method 2 res = ', res);
|
||||
console.log('Method 2: res = ', res);
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
/* Bubble sort */
|
||||
function bubbleSort(nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
@@ -20,30 +20,30 @@ function bubbleSort(nums) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Bubble sort (flag optimization) */
|
||||
/* Bubble sort (flag optimization)*/
|
||||
function bubbleSortWithFlag(nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
let flag = false; // Initialize flag
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
let flag = false; // Initialize the flag
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true; // Record element swap
|
||||
flag = true; // Record that a swap occurred
|
||||
}
|
||||
}
|
||||
if (!flag) break; // No elements were swapped in this round of "bubbling", exit directly
|
||||
if (!flag) break; // Exit immediately if this pass made no swaps
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
bubbleSort(nums);
|
||||
console.log('After bubble sort, nums =', nums);
|
||||
console.log('After bubble sort, array =', nums);
|
||||
|
||||
const nums1 = [4, 1, 3, 1, 5, 2];
|
||||
bubbleSortWithFlag(nums1);
|
||||
console.log('After bubble sort, nums =', nums1);
|
||||
console.log('After bubble sort, array =', nums1);
|
||||
|
||||
@@ -6,25 +6,25 @@
|
||||
|
||||
/* Bucket sort */
|
||||
function bucketSort(nums) {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
// Initialize ceil(n/2) buckets, aiming for about 2 elements per bucket
|
||||
const k = nums.length / 2;
|
||||
const buckets = [];
|
||||
for (let i = 0; i < k; i++) {
|
||||
buckets.push([]);
|
||||
}
|
||||
// 1. Distribute array elements into various buckets
|
||||
// 1. Distribute the array elements among the buckets
|
||||
for (const num of nums) {
|
||||
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
|
||||
// The input range is [0, 1); floor(num * k) maps values to indices from 0 to ceil(k)-1
|
||||
const i = Math.floor(num * k);
|
||||
// Add num to bucket i
|
||||
buckets[i].push(num);
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for (const bucket of buckets) {
|
||||
// Use built-in sorting function, can also replace with other sorting algorithms
|
||||
// Use the built-in sorting function, or replace it with another sorting algorithm
|
||||
bucket.sort((a, b) => a - b);
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
// 3. Traverse the buckets to combine the results
|
||||
let i = 0;
|
||||
for (const bucket of buckets) {
|
||||
for (const num of bucket) {
|
||||
@@ -33,7 +33,7 @@ function bucketSort(nums) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37];
|
||||
bucketSort(nums);
|
||||
console.log('After bucket sort, nums =', nums);
|
||||
|
||||
@@ -5,17 +5,17 @@
|
||||
*/
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
// Simple implementation; cannot be used to sort objects
|
||||
function countingSortNaive(nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
// 1. Find the maximum array element m
|
||||
let m = Math.max(...nums);
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
const counter = new Array(m + 1).fill(0);
|
||||
for (const num of nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
// 3. Traverse counter and fill the original array nums with the elements
|
||||
let i = 0;
|
||||
for (let num = 0; num < m + 1; num++) {
|
||||
for (let j = 0; j < counter[num]; j++, i++) {
|
||||
@@ -25,37 +25,37 @@ function countingSortNaive(nums) {
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
// Full implementation; stable and adaptable to sorting objects
|
||||
function countingSort(nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
// 1. Find the maximum array element m
|
||||
let m = Math.max(...nums);
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
const counter = new Array(m + 1).fill(0);
|
||||
for (const num of nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// counter[num]-1 is the last index where num appears in res
|
||||
// 3. Compute prefix sums of counter to convert occurrence counts into end positions
|
||||
// That is, counter[num]-1 is the index of the last occurrence of num in res
|
||||
for (let i = 0; i < m; i++) {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. Traverse nums in reverse order, placing each element into the result array res
|
||||
// Initialize the array res to record results
|
||||
// 4. Traverse nums in reverse and place each element in the result array res
|
||||
// Initialize array res to store the result
|
||||
const n = nums.length;
|
||||
const res = new Array(n);
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
const num = nums[i];
|
||||
res[counter[num] - 1] = num; // Place num at the corresponding index
|
||||
counter[num]--; // Decrement the prefix sum by 1, getting the next index to place num
|
||||
counter[num]--; // Decrement the prefix sum by 1 to determine where to place the next occurrence of num
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
// Overwrite the original array nums with the result array res
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
countingSortNaive(nums);
|
||||
console.log('After counting sort (cannot sort objects), nums =', nums);
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
/* Sift down from node i in a heap of size n */
|
||||
function siftDown(nums, n, i) {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
let l = 2 * i + 1;
|
||||
let r = 2 * i + 2;
|
||||
let ma = i;
|
||||
@@ -17,33 +17,33 @@ function siftDown(nums, n, i) {
|
||||
if (r < n && nums[r] > nums[ma]) {
|
||||
ma = r;
|
||||
}
|
||||
// Swap two nodes
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma === i) {
|
||||
break;
|
||||
}
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
[nums[i], nums[ma]] = [nums[ma], nums[i]];
|
||||
// Loop downwards heapification
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
function heapSort(nums) {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
// Build the heap by sifting down from every non-leaf node
|
||||
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
|
||||
siftDown(nums, nums.length, i);
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
// Extract the largest element from the heap, repeating for n-1 rounds
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Delete node
|
||||
// Swap the root with the rightmost leaf on the last level (the first and last elements of the current heap)
|
||||
[nums[0], nums[i]] = [nums[i], nums[0]];
|
||||
// Start heapifying the root node, from top to bottom
|
||||
// Sift down starting at the root
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
heapSort(nums);
|
||||
console.log('After heap sort, nums =', nums);
|
||||
|
||||
@@ -6,20 +6,20 @@
|
||||
|
||||
/* Insertion sort */
|
||||
function insertionSort(nums) {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
// Outer loop: the sorted range is [0, i-1]
|
||||
for (let i = 1; i < nums.length; i++) {
|
||||
let base = nums[i],
|
||||
j = i - 1;
|
||||
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
|
||||
// Inner loop: insert base at the correct position in the sorted range [0, i-1]
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
|
||||
nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = base; // Assign base to the correct position
|
||||
nums[j + 1] = base; // Place base at the correct position
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
insertionSort(nums);
|
||||
console.log('After insertion sort, nums =', nums);
|
||||
|
||||
@@ -4,16 +4,16 @@
|
||||
* Author: IsChristina (christinaxia77@foxmail.com)
|
||||
*/
|
||||
|
||||
/* Merge left subarray and right subarray */
|
||||
/* Merge the left and right subarrays */
|
||||
function merge(nums, left, mid, right) {
|
||||
// Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged results
|
||||
// The left subarray spans [left, mid], and the right subarray spans [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged result
|
||||
const tmp = new Array(right - left + 1);
|
||||
// Initialize the start indices of the left and right subarrays
|
||||
// Initialize the starting indices of the left and right subarrays
|
||||
let i = left,
|
||||
j = mid + 1,
|
||||
k = 0;
|
||||
// While both subarrays still have elements, compare and copy the smaller element into the temporary array
|
||||
// While both subarrays have elements remaining, compare them and copy the smaller element into the temporary array
|
||||
while (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j]) {
|
||||
tmp[k++] = nums[i++];
|
||||
@@ -28,7 +28,7 @@ function merge(nums, left, mid, right) {
|
||||
while (j <= right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// Copy the elements from the temporary array tmp back to the original array nums at the corresponding interval
|
||||
// Copy the elements of temporary array tmp back into the corresponding range of the original array nums
|
||||
for (k = 0; k < tmp.length; k++) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
@@ -36,17 +36,17 @@ function merge(nums, left, mid, right) {
|
||||
|
||||
/* Merge sort */
|
||||
function mergeSort(nums, left, right) {
|
||||
// Termination condition
|
||||
if (left >= right) return; // Terminate recursion when subarray length is 1
|
||||
// Divide and conquer stage
|
||||
let mid = Math.floor(left + (right - left) / 2); // Calculate midpoint
|
||||
mergeSort(nums, left, mid); // Recursively process the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recursively process the right subarray
|
||||
// Merge stage
|
||||
// Base case
|
||||
if (left >= right) return; // Stop recursing when the subarray has at most one element
|
||||
// Divide phase
|
||||
let mid = Math.floor(left + (right - left) / 2); // Calculate the midpoint
|
||||
mergeSort(nums, left, mid); // Recurse on the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recurse on the right subarray
|
||||
// Merge phase
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [7, 3, 2, 6, 0, 1, 5, 4];
|
||||
mergeSort(nums, 0, nums.length - 1);
|
||||
console.log('After merge sort, nums =', nums);
|
||||
|
||||
@@ -6,39 +6,39 @@
|
||||
|
||||
/* Quick sort class */
|
||||
class QuickSort {
|
||||
/* Swap elements */
|
||||
/* Swap the elements */
|
||||
swap(nums, i, j) {
|
||||
let tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
/* Two-pointer partitioning */
|
||||
partition(nums, left, right) {
|
||||
// Use nums[left] as the pivot
|
||||
let i = left,
|
||||
j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left]) {
|
||||
j -= 1; // Search from right to left for the first element smaller than the pivot
|
||||
j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
}
|
||||
while (i < j && nums[i] <= nums[left]) {
|
||||
i += 1; // Search from left to right for the first element greater than the pivot
|
||||
i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
}
|
||||
// Swap elements
|
||||
// Swap the elements
|
||||
this.swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
this.swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
this.swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
quickSort(nums, left, right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
// Stop recursing when the subarray has at most one element
|
||||
if (left >= right) return;
|
||||
// Sentinel partition
|
||||
// Two-pointer partitioning
|
||||
const pivot = this.partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
// Recurse on the left and right subarrays
|
||||
this.quickSort(nums, left, pivot - 1);
|
||||
this.quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
@@ -46,7 +46,7 @@ class QuickSort {
|
||||
|
||||
/* Quick sort class (median pivot optimization) */
|
||||
class QuickSortMedian {
|
||||
/* Swap elements */
|
||||
/* Swap the elements */
|
||||
swap(nums, i, j) {
|
||||
let tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
@@ -58,14 +58,14 @@ class QuickSortMedian {
|
||||
let l = nums[left],
|
||||
m = nums[mid],
|
||||
r = nums[right];
|
||||
// m is between l and r
|
||||
// m lies between l and r
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l)) return mid;
|
||||
// l is between m and r
|
||||
// l lies between m and r
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m)) return left;
|
||||
return right;
|
||||
}
|
||||
|
||||
/* Sentinel partition (median of three) */
|
||||
/* Two-pointer partitioning (median of three) */
|
||||
partition(nums, left, right) {
|
||||
// Select the median of three candidate elements
|
||||
let med = this.medianThree(
|
||||
@@ -74,27 +74,27 @@ class QuickSortMedian {
|
||||
Math.floor((left + right) / 2),
|
||||
right
|
||||
);
|
||||
// Swap the median to the array's leftmost position
|
||||
// Swap the median into the leftmost position of the current subarray
|
||||
this.swap(nums, left, med);
|
||||
// Use nums[left] as the pivot
|
||||
let i = left,
|
||||
j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left]) j--; // Search from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Search from left to right for the first element greater than the pivot
|
||||
while (i < j && nums[j] >= nums[left]) j--; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Scan from left to right for the first element larger than the pivot
|
||||
this.swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
this.swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
this.swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
quickSort(nums, left, right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
// Stop recursing when the subarray has at most one element
|
||||
if (left >= right) return;
|
||||
// Sentinel partition
|
||||
// Two-pointer partitioning
|
||||
const pivot = this.partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
// Recurse on the left and right subarrays
|
||||
this.quickSort(nums, left, pivot - 1);
|
||||
this.quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
@@ -102,60 +102,60 @@ class QuickSortMedian {
|
||||
|
||||
/* Quick sort class (recursion depth optimization) */
|
||||
class QuickSortTailCall {
|
||||
/* Swap elements */
|
||||
/* Swap the elements */
|
||||
swap(nums, i, j) {
|
||||
let tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
/* Two-pointer partitioning */
|
||||
partition(nums, left, right) {
|
||||
// Use nums[left] as the pivot
|
||||
let i = left,
|
||||
j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left]) j--; // Search from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Search from left to right for the first element greater than the pivot
|
||||
while (i < j && nums[j] >= nums[left]) j--; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left]) i++; // Scan from left to right for the first element larger than the pivot
|
||||
this.swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
this.swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
this.swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
quickSort(nums, left, right) {
|
||||
// Terminate when subarray length is 1
|
||||
// Stop when the subarray has at most one element
|
||||
while (left < right) {
|
||||
// Sentinel partition operation
|
||||
// Perform two-pointer partitioning
|
||||
let pivot = this.partition(nums, left, right);
|
||||
// Perform quick sort on the shorter of the two subarrays
|
||||
// Apply quick sort to the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
this.quickSort(nums, left, pivot - 1); // Recursively sort the left subarray
|
||||
left = pivot + 1; // Remaining unsorted interval is [pivot + 1, right]
|
||||
left = pivot + 1; // The remaining unsorted range is [pivot + 1, right]
|
||||
} else {
|
||||
this.quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // Remaining unsorted interval is [left, pivot - 1]
|
||||
right = pivot - 1; // The remaining unsorted range is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Quick sort */
|
||||
/* Driver code */
|
||||
/* Quick sort */
|
||||
const nums = [2, 4, 1, 0, 3, 5];
|
||||
const quickSort = new QuickSort();
|
||||
quickSort.quickSort(nums, 0, nums.length - 1);
|
||||
console.log('After quick sort, nums =', nums);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
/* Quick sort (median pivot optimization) */
|
||||
const nums1 = [2, 4, 1, 0, 3, 5];
|
||||
const quickSortMedian = new QuickSortMedian();
|
||||
quickSortMedian.quickSort(nums1, 0, nums1.length - 1);
|
||||
console.log('After quick sort (median pivot optimization), nums =', nums1);
|
||||
console.log('After quick sort (median pivot optimization), nums1 =', nums1);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
const nums2 = [2, 4, 1, 0, 3, 5];
|
||||
const quickSortTailCall = new QuickSortTailCall();
|
||||
quickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
|
||||
console.log('After quick sort (recursion depth optimization), nums =', nums2);
|
||||
console.log('After quick sort (recursion depth optimization), nums2 =', nums2);
|
||||
|
||||
@@ -4,35 +4,35 @@
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Get the k-th digit of element num, where exp = 10^(k-1) */
|
||||
/* Get the k-th digit of num, where exp = 10^(k-1) */
|
||||
function digit(num, exp) {
|
||||
// Passing exp instead of k can avoid repeated expensive exponentiation here
|
||||
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
|
||||
return Math.floor(num / exp) % 10;
|
||||
}
|
||||
|
||||
/* Counting sort (based on nums k-th digit) */
|
||||
/* Counting sort (sort nums by the k-th digit) */
|
||||
function countingSortDigit(nums, exp) {
|
||||
// Decimal digit range is 0~9, therefore need a bucket array of length 10
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs length 10
|
||||
const counter = new Array(10).fill(0);
|
||||
const n = nums.length;
|
||||
// Count the occurrence of digits 0~9
|
||||
// Count the occurrences of each digit from 0 to 9
|
||||
for (let i = 0; i < n; i++) {
|
||||
const d = digit(nums[i], exp); // Get the k-th digit of nums[i], noted as d
|
||||
counter[d]++; // Count the occurrence of digit d
|
||||
const d = digit(nums[i], exp); // Get the k-th digit of nums[i] and store it in d
|
||||
counter[d]++; // Count the occurrences of digit d
|
||||
}
|
||||
// Calculate prefix sum, converting "occurrence count" into "array index"
|
||||
// Compute prefix sums to convert occurrence counts into array positions
|
||||
for (let i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse, based on bucket statistics, place each element into res
|
||||
// Traverse in reverse and place each element into res according to the bucket counts
|
||||
const res = new Array(n).fill(0);
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
const d = digit(nums[i], exp);
|
||||
const j = counter[d] - 1; // Get the index j for d in the array
|
||||
const j = counter[d] - 1; // Get the destination index j for digit d in the array
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d]--; // Decrease the count of d by 1
|
||||
counter[d]--; // Decrease the count for d by 1
|
||||
}
|
||||
// Use result to overwrite the original array nums
|
||||
// Overwrite the original array nums with the result
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
@@ -40,19 +40,19 @@ function countingSortDigit(nums, exp) {
|
||||
|
||||
/* Radix sort */
|
||||
function radixSort(nums) {
|
||||
// Get the maximum element of the array, used to determine the maximum number of digits
|
||||
// Get the largest array element to determine the maximum number of digits
|
||||
let m = Math.max(... nums);
|
||||
// Traverse from the lowest to the highest digit
|
||||
// Process digits from least significant to most significant
|
||||
for (let exp = 1; exp <= m; exp *= 10) {
|
||||
// Perform counting sort on the k-th digit of array elements
|
||||
// Apply counting sort to the k-th digit of the array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// i.e., exp = 10^(k-1)
|
||||
// That is, exp = 10^(k-1)
|
||||
countingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [
|
||||
10546151, 35663510, 42865989, 34862445, 81883077, 88906420, 72429244,
|
||||
30524779, 82060337, 63832996,
|
||||
|
||||
@@ -7,21 +7,21 @@
|
||||
/* Selection sort */
|
||||
function selectionSort(nums) {
|
||||
let n = nums.length;
|
||||
// Outer loop: unsorted interval is [i, n-1]
|
||||
// Outer loop: the unsorted range is [i, n-1]
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
// Inner loop: find the smallest element within the unsorted interval
|
||||
// Inner loop: find the smallest element in the unsorted range
|
||||
let k = i;
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k]) {
|
||||
k = j; // Record the index of the smallest element
|
||||
}
|
||||
}
|
||||
// Swap the smallest element with the first element of the unsorted interval
|
||||
// Swap the smallest element with the first element of the unsorted range
|
||||
[nums[i], nums[k]] = [nums[k], nums[i]];
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
selectionSort(nums);
|
||||
console.log('After selection sort, nums =', nums);
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Double-ended queue based on circular array implementation */
|
||||
/* Deque implemented with a circular array */
|
||||
class ArrayDeque {
|
||||
#nums; // Array for storing double-ended queue elements
|
||||
#front; // Front pointer, points to the front of the queue element
|
||||
#queSize; // Double-ended queue length
|
||||
#nums; // Array for storing deque elements
|
||||
#front; // Front pointer, pointing to the first element
|
||||
#queSize; // Deque size
|
||||
|
||||
/* Constructor */
|
||||
constructor(capacity) {
|
||||
@@ -17,89 +17,89 @@ class ArrayDeque {
|
||||
this.#queSize = 0;
|
||||
}
|
||||
|
||||
/* Get the capacity of the double-ended queue */
|
||||
/* Get the deque capacity */
|
||||
capacity() {
|
||||
return this.#nums.length;
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
size() {
|
||||
return this.#queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
isEmpty() {
|
||||
return this.#queSize === 0;
|
||||
}
|
||||
|
||||
/* Calculate circular array index */
|
||||
/* Calculate an index in the circular array */
|
||||
index(i) {
|
||||
// Use modulo operation to wrap the array head and tail together
|
||||
// When i passes the tail of the array, return to the head
|
||||
// When i passes the head of the array, return to the tail
|
||||
// Use modulo to connect the end of the array to its beginning
|
||||
// When i passes the end of the array, wrap around to the beginning
|
||||
// When i passes the beginning of the array, wrap around to the end
|
||||
return (i + this.capacity()) % this.capacity();
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
/* Enqueue at the front */
|
||||
pushFirst(num) {
|
||||
if (this.#queSize === this.capacity()) {
|
||||
console.log('Double-ended queue is full');
|
||||
console.log('Deque is full');
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap front around to the tail after passing the head of the array
|
||||
// Add num to the front of the queue
|
||||
// Move the front pointer one position to the left
|
||||
// Use modulo to wrap front to the end when it passes the beginning of the array
|
||||
this.#front = this.index(this.#front - 1);
|
||||
// Add num to front of queue
|
||||
// Add num to the front
|
||||
this.#nums[this.#front] = num;
|
||||
this.#queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
/* Enqueue at the rear */
|
||||
pushLast(num) {
|
||||
if (this.#queSize === this.capacity()) {
|
||||
console.log('Double-ended queue is full');
|
||||
console.log('Deque is full');
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
// Calculate the rear pointer, which points one position past the last element
|
||||
const rear = this.index(this.#front + this.#queSize);
|
||||
// Front pointer moves one position backward
|
||||
// Add num to the rear
|
||||
this.#nums[rear] = num;
|
||||
this.#queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
/* Dequeue from the front */
|
||||
popFirst() {
|
||||
const num = this.peekFirst();
|
||||
// Move front pointer backward by one position
|
||||
// Advance the front pointer by one position
|
||||
this.#front = this.index(this.#front + 1);
|
||||
this.#queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
/* Dequeue from the rear */
|
||||
popLast() {
|
||||
const num = this.peekLast();
|
||||
this.#queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
peekFirst() {
|
||||
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
|
||||
if (this.isEmpty()) throw new Error('Deque is empty');
|
||||
return this.#nums[this.#front];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access the rear element */
|
||||
peekLast() {
|
||||
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
|
||||
// Initialize double-ended queue
|
||||
if (this.isEmpty()) throw new Error('Deque is empty');
|
||||
// Calculate the index of the last element
|
||||
const last = this.index(this.#front + this.#queSize - 1);
|
||||
return this.#nums[last];
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
/* Return an array for printing */
|
||||
toArray() {
|
||||
// Elements enqueue
|
||||
// Convert only the list elements within the occupied range
|
||||
const res = [];
|
||||
for (let i = 0, j = this.#front; i < this.#queSize; i++, j++) {
|
||||
res[i] = this.#nums[this.index(j)];
|
||||
@@ -108,8 +108,8 @@ class ArrayDeque {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Driver code */
|
||||
/* Initialize the deque */
|
||||
const capacity = 5;
|
||||
const deque = new ArrayDeque(capacity);
|
||||
deque.pushLast(3);
|
||||
@@ -117,40 +117,40 @@ deque.pushLast(2);
|
||||
deque.pushLast(5);
|
||||
console.log('Deque deque = [' + deque.toArray() + ']');
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
const peekFirst = deque.peekFirst();
|
||||
console.log('Front element peekFirst = ' + peekFirst);
|
||||
const peekLast = deque.peekLast();
|
||||
console.log('Rear element peekLast = ' + peekLast);
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
deque.pushLast(4);
|
||||
console.log('After element 4 enqueues at rear, deque = [' + deque.toArray() + ']');
|
||||
console.log('After enqueuing 4 at the rear, deque = [' + deque.toArray() + ']');
|
||||
deque.pushFirst(1);
|
||||
console.log('After element 1 enqueues at front, deque = [' + deque.toArray() + ']');
|
||||
console.log('After enqueuing 1 at the front, deque = [' + deque.toArray() + ']');
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
const popLast = deque.popLast();
|
||||
console.log(
|
||||
'Rear dequeue element = ' +
|
||||
'Element dequeued from the rear = ' +
|
||||
popLast +
|
||||
', after rear dequeue deque = [' +
|
||||
'; after removing from the rear, deque = [' +
|
||||
deque.toArray() +
|
||||
']'
|
||||
);
|
||||
const popFirst = deque.popFirst();
|
||||
console.log(
|
||||
'Front dequeue element = ' +
|
||||
'Element dequeued from the front = ' +
|
||||
popFirst +
|
||||
', after front dequeue deque = [' +
|
||||
'; after removing from the front, deque = [' +
|
||||
deque.toArray() +
|
||||
']'
|
||||
);
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
const size = deque.size();
|
||||
console.log('Double-ended queue length size = ' + size);
|
||||
console.log('Deque size = ' + size);
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
const isEmpty = deque.isEmpty();
|
||||
console.log('Double-ended queue is empty = ' + isEmpty);
|
||||
console.log('Is the deque empty = ' + isEmpty);
|
||||
|
||||
@@ -4,27 +4,27 @@
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Queue based on circular array implementation */
|
||||
/* Queue implemented with a circular array */
|
||||
class ArrayQueue {
|
||||
#nums; // Array for storing queue elements
|
||||
#front = 0; // Front pointer, points to the front of the queue element
|
||||
#queSize = 0; // Queue length
|
||||
#nums; // Array that stores the queue elements
|
||||
#front = 0; // Front pointer, pointing to the first element
|
||||
#queSize = 0; // Queue size
|
||||
|
||||
constructor(capacity) {
|
||||
this.#nums = new Array(capacity);
|
||||
}
|
||||
|
||||
/* Get the capacity of the queue */
|
||||
/* Get the queue capacity */
|
||||
get capacity() {
|
||||
return this.#nums.length;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
get size() {
|
||||
return this.#queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
isEmpty() {
|
||||
return this.#queSize === 0;
|
||||
}
|
||||
@@ -35,10 +35,10 @@ class ArrayQueue {
|
||||
console.log('Queue is full');
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
// Add num to the rear of the queue
|
||||
// Calculate the rear pointer, which points one position past the last element
|
||||
// Use modulo to wrap rear to the beginning when it passes the end of the array
|
||||
const rear = (this.#front + this.size) % this.capacity;
|
||||
// Front pointer moves one position backward
|
||||
// Add num to the rear
|
||||
this.#nums[rear] = num;
|
||||
this.#queSize++;
|
||||
}
|
||||
@@ -46,21 +46,21 @@ class ArrayQueue {
|
||||
/* Dequeue */
|
||||
pop() {
|
||||
const num = this.peek();
|
||||
// Move front pointer backward by one position, if it passes the tail, return to array head
|
||||
// Advance the front pointer by one position, wrapping to the beginning if it passes the end
|
||||
this.#front = (this.#front + 1) % this.capacity;
|
||||
this.#queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
peek() {
|
||||
if (this.isEmpty()) throw new Error('Queue is empty');
|
||||
return this.#nums[this.#front];
|
||||
}
|
||||
|
||||
/* Return Array */
|
||||
/* Return an Array */
|
||||
toArray() {
|
||||
// Elements enqueue
|
||||
// Convert only the list elements within the occupied range
|
||||
const arr = new Array(this.size);
|
||||
for (let i = 0, j = this.#front; i < this.size; i++, j++) {
|
||||
arr[i] = this.#nums[j % this.capacity];
|
||||
@@ -69,12 +69,12 @@ class ArrayQueue {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access front of the queue element */
|
||||
/* Driver code */
|
||||
/* Initialize the queue */
|
||||
const capacity = 10;
|
||||
const queue = new ArrayQueue(capacity);
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
@@ -82,25 +82,25 @@ queue.push(5);
|
||||
queue.push(4);
|
||||
console.log('Queue queue =', queue.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
const peek = queue.peek();
|
||||
console.log('Front element peek = ' + peek);
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
const pop = queue.pop();
|
||||
console.log('Dequeue element pop = ' + pop + ', after dequeue queue =', queue.toArray());
|
||||
console.log('Dequeued element pop = ' + pop + '; after dequeuing, queue =', queue.toArray());
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
const size = queue.size;
|
||||
console.log('Queue length size = ' + size);
|
||||
console.log('Queue size = ' + size);
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
const isEmpty = queue.isEmpty();
|
||||
console.log('Queue is empty = ' + isEmpty);
|
||||
console.log('Is the queue empty = ' + isEmpty);
|
||||
|
||||
/* Test circular array */
|
||||
/* Test the circular array */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
queue.push(i);
|
||||
queue.pop();
|
||||
console.log('Round ' + i + ' rounds of enqueue + dequeue, queue =', queue.toArray());
|
||||
console.log('Round ' + i + ' : after enqueue + dequeue, queue =', queue.toArray());
|
||||
}
|
||||
|
||||
@@ -4,19 +4,19 @@
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Stack based on array implementation */
|
||||
/* Stack implemented with an array */
|
||||
class ArrayStack {
|
||||
#stack;
|
||||
constructor() {
|
||||
this.#stack = [];
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
get size() {
|
||||
return this.#stack.length;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
/* Check whether the stack is empty */
|
||||
isEmpty() {
|
||||
return this.#stack.length === 0;
|
||||
}
|
||||
@@ -32,23 +32,23 @@ class ArrayStack {
|
||||
return this.#stack.pop();
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
top() {
|
||||
if (this.isEmpty()) throw new Error('Stack is empty');
|
||||
return this.#stack[this.#stack.length - 1];
|
||||
}
|
||||
|
||||
/* Return Array */
|
||||
/* Return an Array */
|
||||
toArray() {
|
||||
return this.#stack;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access top of the stack element */
|
||||
/* Driver code */
|
||||
/* Initialize the stack */
|
||||
const stack = new ArrayStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
/* Push elements onto the stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
@@ -57,19 +57,19 @@ stack.push(4);
|
||||
console.log('Stack stack = ');
|
||||
console.log(stack.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
const top = stack.top();
|
||||
console.log('Stack top element top = ' + top);
|
||||
console.log('Top element top = ' + top);
|
||||
|
||||
/* Element pop from stack */
|
||||
/* Pop an element from the stack */
|
||||
const pop = stack.pop();
|
||||
console.log('Pop element pop = ' + pop + ', after pop, stack = ');
|
||||
console.log('Popped element pop = ' + pop + '; after popping, stack = ');
|
||||
console.log(stack.toArray());
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
const size = stack.size;
|
||||
console.log('Stack length size = ' + size);
|
||||
console.log('Stack size = ' + size);
|
||||
|
||||
/* Check if empty */
|
||||
/* Check whether it is empty */
|
||||
const isEmpty = stack.isEmpty();
|
||||
console.log('Stack is empty = ' + isEmpty);
|
||||
console.log('Is the stack empty = ' + isEmpty);
|
||||
|
||||
@@ -4,41 +4,41 @@
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Get the length of the double-ended queue */
|
||||
// JavaScript has no built-in deque, can only use Array as deque
|
||||
/* Driver code */
|
||||
/* Initialize the deque */
|
||||
// JavaScript has no built-in deque; use an Array as a deque
|
||||
const deque = [];
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
deque.push(2);
|
||||
deque.push(5);
|
||||
deque.push(4);
|
||||
// Note: due to array, unshift() method has O(n) time complexity
|
||||
// Note: because this uses an array, unshift() has O(n) time complexity
|
||||
deque.unshift(3);
|
||||
deque.unshift(1);
|
||||
console.log('Double-ended queue deque = ', deque);
|
||||
console.log('Deque deque = ', deque);
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
const peekFirst = deque[0];
|
||||
console.log('Front element peekFirst = ' + peekFirst);
|
||||
const peekLast = deque[deque.length - 1];
|
||||
console.log('Rear element peekLast = ' + peekLast);
|
||||
|
||||
/* Element dequeue */
|
||||
// Note: due to array, shift() method has O(n) time complexity
|
||||
/* Dequeue an element */
|
||||
// Note: because this uses an array, shift() has O(n) time complexity
|
||||
const popFront = deque.shift();
|
||||
console.log(
|
||||
'Front dequeue element popFront = ' + popFront + ', after front dequeue, deque = ' + deque
|
||||
'Element removed from the front, popFront = ' + popFront + ', after dequeuing from the front, deque = ' + deque
|
||||
);
|
||||
const popBack = deque.pop();
|
||||
console.log(
|
||||
'Dequeue rear element popBack = ' + popBack + ', after rear dequeue, deque = ' + deque
|
||||
'Element removed from the rear, popBack = ' + popBack + ', after dequeuing from the rear, deque = ' + deque
|
||||
);
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
const size = deque.length;
|
||||
console.log('Double-ended queue length size = ' + size);
|
||||
console.log('Deque size = ' + size);
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
const isEmpty = size === 0;
|
||||
console.log('Double-ended queue is empty = ' + isEmpty);
|
||||
console.log('Is the deque empty = ' + isEmpty);
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
|
||||
/* Doubly linked list node */
|
||||
class ListNode {
|
||||
prev; // Predecessor node reference (pointer)
|
||||
next; // Successor node reference (pointer)
|
||||
prev; // Reference (pointer) to the previous node
|
||||
next; // Reference (pointer) to the next node
|
||||
val; // Node value
|
||||
|
||||
constructor(val) {
|
||||
@@ -17,11 +17,11 @@ class ListNode {
|
||||
}
|
||||
}
|
||||
|
||||
/* Double-ended queue based on doubly linked list implementation */
|
||||
/* Deque implemented with a doubly linked list */
|
||||
class LinkedListDeque {
|
||||
#front; // Head node front
|
||||
#rear; // Tail node rear
|
||||
#queSize; // Length of the double-ended queue
|
||||
#queSize; // Deque size
|
||||
|
||||
constructor() {
|
||||
this.#front = null;
|
||||
@@ -29,7 +29,7 @@ class LinkedListDeque {
|
||||
this.#queSize = 0;
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue operation */
|
||||
/* Enqueue at the rear */
|
||||
pushLast(val) {
|
||||
const node = new ListNode(val);
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
@@ -40,12 +40,12 @@ class LinkedListDeque {
|
||||
// Add node to the tail of the linked list
|
||||
this.#rear.next = node;
|
||||
node.prev = this.#rear;
|
||||
this.#rear = node; // Update tail node
|
||||
this.#rear = node; // Update the tail node
|
||||
}
|
||||
this.#queSize++;
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue operation */
|
||||
/* Enqueue at the front */
|
||||
pushFirst(val) {
|
||||
const node = new ListNode(val);
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
@@ -56,76 +56,76 @@ class LinkedListDeque {
|
||||
// Add node to the head of the linked list
|
||||
this.#front.prev = node;
|
||||
node.next = this.#front;
|
||||
this.#front = node; // Update head node
|
||||
this.#front = node; // Update the head node
|
||||
}
|
||||
this.#queSize++;
|
||||
}
|
||||
|
||||
/* Temporarily store tail node value */
|
||||
/* Dequeue from the rear */
|
||||
popLast() {
|
||||
if (this.#queSize === 0) {
|
||||
return null;
|
||||
}
|
||||
const value = this.#rear.val; // Store tail node value
|
||||
// When the deque has one element, front and rear point to the same node
|
||||
const value = this.#rear.val; // Store the tail node value
|
||||
// When the queue size is 1, the head and tail point to the same node
|
||||
if (this.#queSize === 1) {
|
||||
this.#front = null;
|
||||
this.#rear = null;
|
||||
}
|
||||
// Update tail node
|
||||
// Remove the tail node
|
||||
else {
|
||||
let temp = this.#rear.prev;
|
||||
temp.next = null;
|
||||
this.#rear.prev = null;
|
||||
this.#rear = temp; // Update tail node
|
||||
this.#rear = temp; // Update the tail node
|
||||
}
|
||||
this.#queSize--;
|
||||
return value;
|
||||
}
|
||||
|
||||
/* Temporarily store head node value */
|
||||
/* Dequeue from the front */
|
||||
popFirst() {
|
||||
if (this.#queSize === 0) {
|
||||
return null;
|
||||
}
|
||||
const value = this.#front.val; // Store the head node value
|
||||
// When the deque has one element, front and rear point to the same node
|
||||
// When the queue size is 1, the head and tail point to the same node
|
||||
if (this.#queSize === 1) {
|
||||
this.#front = null;
|
||||
this.#rear = null;
|
||||
}
|
||||
// Delete head node
|
||||
// Remove the head node
|
||||
else {
|
||||
let temp = this.#front.next;
|
||||
temp.prev = null;
|
||||
this.#front.next = null;
|
||||
this.#front = temp; // Update head node
|
||||
this.#front = temp; // Update the head node
|
||||
}
|
||||
this.#queSize--;
|
||||
return value;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access the rear element */
|
||||
peekLast() {
|
||||
return this.#queSize === 0 ? null : this.#rear.val;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
peekFirst() {
|
||||
return this.#queSize === 0 ? null : this.#front.val;
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
size() {
|
||||
return this.#queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
isEmpty() {
|
||||
return this.#queSize === 0;
|
||||
}
|
||||
|
||||
/* Print deque */
|
||||
/* Print the deque */
|
||||
print() {
|
||||
const arr = [];
|
||||
let temp = this.#front;
|
||||
@@ -137,8 +137,8 @@ class LinkedListDeque {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Driver code */
|
||||
/* Initialize the deque */
|
||||
const linkedListDeque = new LinkedListDeque();
|
||||
linkedListDeque.pushLast(3);
|
||||
linkedListDeque.pushLast(2);
|
||||
@@ -146,32 +146,32 @@ linkedListDeque.pushLast(5);
|
||||
console.log('Deque linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
|
||||
/* Update element */
|
||||
/* Access an element */
|
||||
const peekFirst = linkedListDeque.peekFirst();
|
||||
console.log('Front element peekFirst = ' + peekFirst);
|
||||
const peekLast = linkedListDeque.peekLast();
|
||||
console.log('Rear element peekLast = ' + peekLast);
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
linkedListDeque.pushLast(4);
|
||||
console.log('After element 4 enqueues at rear, linkedListDeque = ');
|
||||
console.log('After enqueuing 4 at the rear, linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
linkedListDeque.pushFirst(1);
|
||||
console.log('After element 1 enqueues at front, linkedListDeque = ');
|
||||
console.log('After enqueuing 1 at the front, linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
const popLast = linkedListDeque.popLast();
|
||||
console.log('Rear dequeue element = ' + popLast + ', after rear dequeue linkedListDeque = ');
|
||||
console.log('Element dequeued from the rear = ' + popLast + '; after removing from the rear, linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
const popFirst = linkedListDeque.popFirst();
|
||||
console.log('Front dequeue element = ' + popFirst + ', after front dequeue linkedListDeque = ');
|
||||
console.log('Element dequeued from the front = ' + popFirst + '; after removing from the front, linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
/* Get the deque size */
|
||||
const size = linkedListDeque.size();
|
||||
console.log('Double-ended queue length size = ' + size);
|
||||
console.log('Deque size = ' + size);
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
/* Check whether the deque is empty */
|
||||
const isEmpty = linkedListDeque.isEmpty();
|
||||
console.log('Double-ended queue is empty = ' + isEmpty);
|
||||
console.log('Is the deque empty = ' + isEmpty);
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
|
||||
const { ListNode } = require('../modules/ListNode');
|
||||
|
||||
/* Queue based on linked list implementation */
|
||||
/* Queue implemented with a linked list */
|
||||
class LinkedListQueue {
|
||||
#front; // Front node #front
|
||||
#rear; // Rear node #rear
|
||||
#front; // Head node #front
|
||||
#rear; // Tail node #rear
|
||||
#queSize = 0;
|
||||
|
||||
constructor() {
|
||||
@@ -17,12 +17,12 @@ class LinkedListQueue {
|
||||
this.#rear = null;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
get size() {
|
||||
return this.#queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
isEmpty() {
|
||||
return this.size === 0;
|
||||
}
|
||||
@@ -31,11 +31,11 @@ class LinkedListQueue {
|
||||
push(num) {
|
||||
// Add num after the tail node
|
||||
const node = new ListNode(num);
|
||||
// If the queue is empty, make both front and rear point to the node
|
||||
// If the queue is empty, make both the head and tail point to this node
|
||||
if (!this.#front) {
|
||||
this.#front = node;
|
||||
this.#rear = node;
|
||||
// If the queue is not empty, add the node after the tail node
|
||||
// If the queue is not empty, add this node after the tail node
|
||||
} else {
|
||||
this.#rear.next = node;
|
||||
this.#rear = node;
|
||||
@@ -46,19 +46,19 @@ class LinkedListQueue {
|
||||
/* Dequeue */
|
||||
pop() {
|
||||
const num = this.peek();
|
||||
// Delete head node
|
||||
// Remove the head node
|
||||
this.#front = this.#front.next;
|
||||
this.#queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
peek() {
|
||||
if (this.size === 0) throw new Error('Queue is empty');
|
||||
return this.#front.val;
|
||||
}
|
||||
|
||||
/* Convert linked list to Array and return */
|
||||
/* Convert the linked list to an Array and return it */
|
||||
toArray() {
|
||||
let node = this.#front;
|
||||
const res = new Array(this.size);
|
||||
@@ -70,11 +70,11 @@ class LinkedListQueue {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access front of the queue element */
|
||||
/* Driver code */
|
||||
/* Initialize the queue */
|
||||
const queue = new LinkedListQueue();
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
@@ -82,18 +82,18 @@ queue.push(5);
|
||||
queue.push(4);
|
||||
console.log('Queue queue = ' + queue.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
const peek = queue.peek();
|
||||
console.log('Front element peek = ' + peek);
|
||||
|
||||
/* Element dequeue */
|
||||
/* Dequeue an element */
|
||||
const pop = queue.pop();
|
||||
console.log('Dequeue element pop = ' + pop + ', after dequeue, queue = ' + queue.toArray());
|
||||
console.log('Dequeued element pop = ' + pop + '; after dequeuing, queue = ' + queue.toArray());
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
const size = queue.size;
|
||||
console.log('Queue length size = ' + size);
|
||||
console.log('Queue size = ' + size);
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
const isEmpty = queue.isEmpty();
|
||||
console.log('Queue is empty = ' + isEmpty);
|
||||
console.log('Is the queue empty = ' + isEmpty);
|
||||
|
||||
@@ -6,21 +6,21 @@
|
||||
|
||||
const { ListNode } = require('../modules/ListNode');
|
||||
|
||||
/* Stack based on linked list implementation */
|
||||
/* Stack implemented with a linked list */
|
||||
class LinkedListStack {
|
||||
#stackPeek; // Use head node as stack top
|
||||
#stkSize = 0; // Stack length
|
||||
#stackPeek; // Use the head node as the stack top
|
||||
#stkSize = 0; // Stack size
|
||||
|
||||
constructor() {
|
||||
this.#stackPeek = null;
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
get size() {
|
||||
return this.#stkSize;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
/* Check whether the stack is empty */
|
||||
isEmpty() {
|
||||
return this.size === 0;
|
||||
}
|
||||
@@ -41,13 +41,13 @@ class LinkedListStack {
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
peek() {
|
||||
if (!this.#stackPeek) throw new Error('Stack is empty');
|
||||
return this.#stackPeek.val;
|
||||
}
|
||||
|
||||
/* Convert linked list to Array and return */
|
||||
/* Convert the linked list to an Array and return it */
|
||||
toArray() {
|
||||
let node = this.#stackPeek;
|
||||
const res = new Array(this.size);
|
||||
@@ -59,11 +59,11 @@ class LinkedListStack {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access top of the stack element */
|
||||
/* Driver code */
|
||||
/* Initialize the stack */
|
||||
const stack = new LinkedListStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
/* Push elements onto the stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
@@ -71,18 +71,18 @@ stack.push(5);
|
||||
stack.push(4);
|
||||
console.log('Stack stack = ' + stack.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
const peek = stack.peek();
|
||||
console.log('Stack top element peek = ' + peek);
|
||||
console.log('Top element peek = ' + peek);
|
||||
|
||||
/* Element pop from stack */
|
||||
/* Pop an element from the stack */
|
||||
const pop = stack.pop();
|
||||
console.log('Pop element pop = ' + pop + ', after pop, stack = ' + stack.toArray());
|
||||
console.log('Popped element pop = ' + pop + '; after popping, stack = ' + stack.toArray());
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
const size = stack.size;
|
||||
console.log('Stack length size = ' + size);
|
||||
console.log('Stack size = ' + size);
|
||||
|
||||
/* Check if empty */
|
||||
/* Check whether it is empty */
|
||||
const isEmpty = stack.isEmpty();
|
||||
console.log('Stack is empty = ' + isEmpty);
|
||||
console.log('Is the stack empty = ' + isEmpty);
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Access front of the queue element */
|
||||
// JavaScript has no built-in queue, can use Array as queue
|
||||
/* Driver code */
|
||||
/* Initialize the queue */
|
||||
// JavaScript has no built-in queue; an Array can be used as a queue
|
||||
const queue = [];
|
||||
|
||||
/* Elements enqueue */
|
||||
/* Enqueue elements */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
@@ -17,19 +17,19 @@ queue.push(5);
|
||||
queue.push(4);
|
||||
console.log('Queue queue =', queue);
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the front element */
|
||||
const peek = queue[0];
|
||||
console.log('Front element peek =', peek);
|
||||
|
||||
/* Element dequeue */
|
||||
// Underlying is array, so shift() method has O(n) time complexity
|
||||
/* Dequeue an element */
|
||||
// The underlying structure is an array, so shift() has O(n) time complexity
|
||||
const pop = queue.shift();
|
||||
console.log('Dequeue element pop =', pop, ', after dequeue, queue = ', queue);
|
||||
console.log('Dequeued element pop =', pop, '; after dequeuing, queue = ', queue);
|
||||
|
||||
/* Get the length of the queue */
|
||||
/* Get the queue size */
|
||||
const size = queue.length;
|
||||
console.log('Queue length size =', size);
|
||||
console.log('Queue size =', size);
|
||||
|
||||
/* Check if the queue is empty */
|
||||
/* Check whether the queue is empty */
|
||||
const isEmpty = queue.length === 0;
|
||||
console.log('Queue is empty = ', isEmpty);
|
||||
console.log('Is the queue empty = ', isEmpty);
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Access top of the stack element */
|
||||
// JavaScript has no built-in stack class, can use Array as stack
|
||||
/* Driver code */
|
||||
/* Initialize the stack */
|
||||
// JavaScript has no built-in stack class; an Array can be used as a stack
|
||||
const stack = [];
|
||||
|
||||
/* Elements push onto stack */
|
||||
/* Push elements onto the stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
@@ -17,19 +17,19 @@ stack.push(5);
|
||||
stack.push(4);
|
||||
console.log('Stack stack =', stack);
|
||||
|
||||
/* Return list for printing */
|
||||
/* Access the top element */
|
||||
const peek = stack[stack.length - 1];
|
||||
console.log('Stack top element peek =', peek);
|
||||
console.log('Top element peek =', peek);
|
||||
|
||||
/* Element pop from stack */
|
||||
/* Pop an element from the stack */
|
||||
const pop = stack.pop();
|
||||
console.log('Pop element pop =', pop);
|
||||
console.log('After pop, stack =', stack);
|
||||
console.log('Popped element pop =', pop);
|
||||
console.log('After popping, stack =', stack);
|
||||
|
||||
/* Get the length of the stack */
|
||||
/* Get the stack size */
|
||||
const size = stack.length;
|
||||
console.log('Stack length size =', size);
|
||||
console.log('Stack size =', size);
|
||||
|
||||
/* Check if empty */
|
||||
/* Check whether it is empty */
|
||||
const isEmpty = stack.length === 0;
|
||||
console.log('Is stack empty =', isEmpty);
|
||||
console.log('Is the stack empty =', isEmpty);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Binary tree class represented by array */
|
||||
/* Binary tree class using an array representation */
|
||||
class ArrayBinaryTree {
|
||||
#tree;
|
||||
|
||||
@@ -16,29 +16,29 @@ class ArrayBinaryTree {
|
||||
this.#tree = arr;
|
||||
}
|
||||
|
||||
/* List capacity */
|
||||
/* Array length */
|
||||
size() {
|
||||
return this.#tree.length;
|
||||
}
|
||||
|
||||
/* Get value of node at index i */
|
||||
/* Get the value of the node at index i */
|
||||
val(i) {
|
||||
// If index out of bounds, return null to represent empty position
|
||||
// If the index is out of bounds, return null to indicate an empty position
|
||||
if (i < 0 || i >= this.size()) return null;
|
||||
return this.#tree[i];
|
||||
}
|
||||
|
||||
/* Get index of left child node of node at index i */
|
||||
/* Get the left child index of the node at index i */
|
||||
left(i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node of node at index i */
|
||||
/* Get the right child index of the node at index i */
|
||||
right(i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node of node at index i */
|
||||
/* Get the parent index of the node at index i */
|
||||
parent(i) {
|
||||
return Math.floor((i - 1) / 2); // Floor division
|
||||
}
|
||||
@@ -46,7 +46,7 @@ class ArrayBinaryTree {
|
||||
/* Level-order traversal */
|
||||
levelOrder() {
|
||||
let res = [];
|
||||
// Traverse array directly
|
||||
// Traverse the array directly
|
||||
for (let i = 0; i < this.size(); i++) {
|
||||
if (this.val(i) !== null) res.push(this.val(i));
|
||||
}
|
||||
@@ -55,7 +55,7 @@ class ArrayBinaryTree {
|
||||
|
||||
/* Depth-first traversal */
|
||||
#dfs(i, order, res) {
|
||||
// If empty position, return
|
||||
// Return if this position is empty
|
||||
if (this.val(i) === null) return;
|
||||
// Preorder traversal
|
||||
if (order === 'pre') res.push(this.val(i));
|
||||
@@ -89,9 +89,9 @@ class ArrayBinaryTree {
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Initialize binary tree
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
/* Driver code */
|
||||
// Initialize the binary tree
|
||||
// Use a helper function that builds a binary tree directly from an array
|
||||
const arr = Array.of(
|
||||
1,
|
||||
2,
|
||||
@@ -111,37 +111,37 @@ const arr = Array.of(
|
||||
);
|
||||
|
||||
const root = arrToTree(arr);
|
||||
console.log('\nInitialize binary tree\n');
|
||||
console.log('Array representation of binary tree:');
|
||||
console.log('\nInitialize the binary tree\n');
|
||||
console.log('Array representation of the binary tree:');
|
||||
console.log(arr);
|
||||
console.log('Linked list representation of binary tree:');
|
||||
console.log('Linked representation of the binary tree:');
|
||||
printTree(root);
|
||||
|
||||
// Binary tree class represented by array
|
||||
// Binary tree class using an array representation
|
||||
const abt = new ArrayBinaryTree(arr);
|
||||
|
||||
// Access node
|
||||
// Access a node
|
||||
const i = 1;
|
||||
const l = abt.left(i);
|
||||
const r = abt.right(i);
|
||||
const p = abt.parent(i);
|
||||
console.log('\nCurrent node index is ' + i + ', value is ' + abt.val(i));
|
||||
console.log('\nCurrent node index: ' + i + ' with value ' + abt.val(i));
|
||||
console.log(
|
||||
'Its left child node index is ' + l + ', value is ' + (l === null ? 'null' : abt.val(l))
|
||||
'Left child index: ' + l + ' with value ' + (l === null ? 'null' : abt.val(l))
|
||||
);
|
||||
console.log(
|
||||
'Its right child node index is ' + r + ', value is ' + (r === null ? 'null' : abt.val(r))
|
||||
'Right child index: ' + r + ' with value ' + (r === null ? 'null' : abt.val(r))
|
||||
);
|
||||
console.log(
|
||||
'Its parent node index is ' + p + ', value is ' + (p === null ? 'null' : abt.val(p))
|
||||
'Parent index: ' + p + ' with value ' + (p === null ? 'null' : abt.val(p))
|
||||
);
|
||||
|
||||
// Traverse tree
|
||||
// Traverse the tree
|
||||
let res = abt.levelOrder();
|
||||
console.log('\nLevel-order traversal is:' + res);
|
||||
console.log('\nLevel-order traversal:' + res);
|
||||
res = abt.preOrder();
|
||||
console.log('Preorder traversal is:' + res);
|
||||
console.log('Preorder traversal:' + res);
|
||||
res = abt.inOrder();
|
||||
console.log('Inorder traversal is:' + res);
|
||||
console.log('Inorder traversal:' + res);
|
||||
res = abt.postOrder();
|
||||
console.log('Postorder traversal is:' + res);
|
||||
console.log('Postorder traversal:' + res);
|
||||
|
||||
@@ -7,133 +7,133 @@
|
||||
const { TreeNode } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* AVL tree */
|
||||
/* AVL tree*/
|
||||
class AVLTree {
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
this.root = null; // Root node
|
||||
this.root = null; //Root node
|
||||
}
|
||||
|
||||
/* Get node height */
|
||||
/* Get the node height */
|
||||
height(node) {
|
||||
// Empty node height is -1, leaf node height is 0
|
||||
// A null node has height -1; a leaf has height 0
|
||||
return node === null ? -1 : node.height;
|
||||
}
|
||||
|
||||
/* Update node height */
|
||||
/* Update the node height */
|
||||
#updateHeight(node) {
|
||||
// Node height equals the height of the tallest subtree + 1
|
||||
// The node height equals the height of its taller subtree + 1
|
||||
node.height =
|
||||
Math.max(this.height(node.left), this.height(node.right)) + 1;
|
||||
}
|
||||
|
||||
/* Get balance factor */
|
||||
/* Get the balance factor */
|
||||
balanceFactor(node) {
|
||||
// Empty node balance factor is 0
|
||||
// A null node has balance factor 0
|
||||
if (node === null) return 0;
|
||||
// Node balance factor = left subtree height - right subtree height
|
||||
return this.height(node.left) - this.height(node.right);
|
||||
}
|
||||
|
||||
/* Right rotation operation */
|
||||
/* Right rotation */
|
||||
#rightRotate(node) {
|
||||
const child = node.left;
|
||||
const grandChild = child.right;
|
||||
// Using child as pivot, rotate node to the right
|
||||
// Rotate node to the right around child
|
||||
child.right = node;
|
||||
node.left = grandChild;
|
||||
// Update node height
|
||||
// Update the node height
|
||||
this.#updateHeight(node);
|
||||
this.#updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
// Return the root of the rotated subtree
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Left rotation operation */
|
||||
/* Left rotation */
|
||||
#leftRotate(node) {
|
||||
const child = node.right;
|
||||
const grandChild = child.left;
|
||||
// Using child as pivot, rotate node to the left
|
||||
// Rotate node to the left around child
|
||||
child.left = node;
|
||||
node.right = grandChild;
|
||||
// Update node height
|
||||
// Update the node height
|
||||
this.#updateHeight(node);
|
||||
this.#updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
// Return the root of the rotated subtree
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Perform rotation operation to restore balance to this subtree */
|
||||
/* Perform rotations to restore balance in this subtree */
|
||||
#rotate(node) {
|
||||
// Get balance factor of node
|
||||
// Get the balance factor of node
|
||||
const balanceFactor = this.balanceFactor(node);
|
||||
// Left-leaning tree
|
||||
// Left-heavy tree
|
||||
if (balanceFactor > 1) {
|
||||
if (this.balanceFactor(node.left) >= 0) {
|
||||
// Right rotation
|
||||
// Rotate right
|
||||
return this.#rightRotate(node);
|
||||
} else {
|
||||
// First left rotation then right rotation
|
||||
// Rotate left, then right
|
||||
node.left = this.#leftRotate(node.left);
|
||||
return this.#rightRotate(node);
|
||||
}
|
||||
}
|
||||
// Right-leaning tree
|
||||
// Right-heavy tree
|
||||
if (balanceFactor < -1) {
|
||||
if (this.balanceFactor(node.right) <= 0) {
|
||||
// Left rotation
|
||||
// Rotate left
|
||||
return this.#leftRotate(node);
|
||||
} else {
|
||||
// First right rotation then left rotation
|
||||
// Rotate right, then left
|
||||
node.right = this.#rightRotate(node.right);
|
||||
return this.#leftRotate(node);
|
||||
}
|
||||
}
|
||||
// Balanced tree, no rotation needed, return directly
|
||||
// The tree is balanced; return without rotating
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
insert(val) {
|
||||
this.root = this.#insertHelper(this.root, val);
|
||||
}
|
||||
|
||||
/* Recursively insert node (helper method) */
|
||||
/* Insert a node recursively (helper method) */
|
||||
#insertHelper(node, val) {
|
||||
if (node === null) return new TreeNode(val);
|
||||
/* 1. Find insertion position and insert node */
|
||||
/* 1. Find the insertion position and insert the node */
|
||||
if (val < node.val) node.left = this.#insertHelper(node.left, val);
|
||||
else if (val > node.val)
|
||||
node.right = this.#insertHelper(node.right, val);
|
||||
else return node; // Duplicate node not inserted, return directly
|
||||
this.#updateHeight(node); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
else return node; // Return without inserting a duplicate node
|
||||
this.#updateHeight(node); // Update the node height
|
||||
/* 2. Perform rotations to restore balance in this subtree */
|
||||
node = this.#rotate(node);
|
||||
// Return root node of subtree
|
||||
// Return the root of the subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
remove(val) {
|
||||
this.root = this.#removeHelper(this.root, val);
|
||||
}
|
||||
|
||||
/* Recursively delete node (helper method) */
|
||||
/* Remove a node recursively (helper method) */
|
||||
#removeHelper(node, val) {
|
||||
if (node === null) return null;
|
||||
/* 1. Find node and delete */
|
||||
/* 1. Find and remove the node */
|
||||
if (val < node.val) node.left = this.#removeHelper(node.left, val);
|
||||
else if (val > node.val)
|
||||
node.right = this.#removeHelper(node.right, val);
|
||||
else {
|
||||
if (node.left === null || node.right === null) {
|
||||
const child = node.left !== null ? node.left : node.right;
|
||||
// Number of child nodes = 0, delete node directly and return
|
||||
// Number of children = 0: remove node and return
|
||||
if (child === null) return null;
|
||||
// Number of child nodes = 1, delete node directly
|
||||
// Number of children = 1: remove node directly
|
||||
else node = child;
|
||||
} else {
|
||||
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
// Number of children = 2: remove the inorder successor and use its value to replace the current node value
|
||||
let temp = node.right;
|
||||
while (temp.left !== null) {
|
||||
temp = temp.left;
|
||||
@@ -142,47 +142,47 @@ class AVLTree {
|
||||
node.val = temp.val;
|
||||
}
|
||||
}
|
||||
this.#updateHeight(node); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
this.#updateHeight(node); // Update the node height
|
||||
/* 2. Perform rotations to restore balance in this subtree */
|
||||
node = this.#rotate(node);
|
||||
// Return root node of subtree
|
||||
// Return the root of the subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
search(val) {
|
||||
let cur = this.root;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Search in a loop until reaching a null reference beyond a leaf
|
||||
while (cur !== null) {
|
||||
// Target node is in cur's right subtree
|
||||
// The target node lies in the right subtree of cur
|
||||
if (cur.val < val) cur = cur.right;
|
||||
// Target node is in cur's left subtree
|
||||
// The target node lies in the left subtree of cur
|
||||
else if (cur.val > val) cur = cur.left;
|
||||
// Found target node, exit loop
|
||||
// The target node was found; exit the loop
|
||||
else break;
|
||||
}
|
||||
// Return target node
|
||||
// Return the target node
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
|
||||
function testInsert(tree, val) {
|
||||
tree.insert(val);
|
||||
console.log('\nInsert node ' + val + ', AVL tree is');
|
||||
console.log('\nAfter inserting node ' + val + ' the AVL tree is:');
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
function testRemove(tree, val) {
|
||||
tree.remove(val);
|
||||
console.log('\nRemove node ' + val + ', AVL tree is');
|
||||
console.log('\nAfter removing node ' + val + ' the AVL tree is:');
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
|
||||
/* Driver code */
|
||||
/* Initialize an empty AVL tree */
|
||||
const avlTree = new AVLTree();
|
||||
/* Insert node */
|
||||
// Delete nodes
|
||||
/* Insert a node */
|
||||
// Observe how the AVL tree maintains balance after a node is inserted
|
||||
testInsert(avlTree, 1);
|
||||
testInsert(avlTree, 2);
|
||||
testInsert(avlTree, 3);
|
||||
@@ -194,15 +194,15 @@ testInsert(avlTree, 9);
|
||||
testInsert(avlTree, 10);
|
||||
testInsert(avlTree, 6);
|
||||
|
||||
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
|
||||
/* Insert a duplicate node */
|
||||
testInsert(avlTree, 7);
|
||||
|
||||
/* Remove node */
|
||||
// Delete node with degree 1
|
||||
testRemove(avlTree, 8); // Delete node with degree 2
|
||||
testRemove(avlTree, 5); // Remove node with degree 1
|
||||
testRemove(avlTree, 4); // Remove node with degree 2
|
||||
/* Remove a node */
|
||||
// Observe how the AVL tree maintains balance after a node is removed
|
||||
testRemove(avlTree, 8); // Remove a node with 0 children
|
||||
testRemove(avlTree, 5); // Remove a node with 1 child
|
||||
testRemove(avlTree, 4); // Remove a node with 2 children
|
||||
|
||||
/* Search node */
|
||||
/* Look up a node */
|
||||
const node = avlTree.search(7);
|
||||
console.log('\nFound node object is', node, ', node value = ' + node.val);
|
||||
console.log('\nFound node object:', node, ', node value = ' + node.val);
|
||||
|
||||
@@ -11,129 +11,129 @@ const { printTree } = require('../modules/PrintUtil');
|
||||
class BinarySearchTree {
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
// Initialize empty tree
|
||||
// Initialize an empty tree
|
||||
this.root = null;
|
||||
}
|
||||
|
||||
/* Get binary tree root node */
|
||||
/* Get the root of the binary tree */
|
||||
getRoot() {
|
||||
return this.root;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
search(num) {
|
||||
let cur = this.root;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Search in a loop until reaching a null reference beyond a leaf
|
||||
while (cur !== null) {
|
||||
// Target node is in cur's right subtree
|
||||
// The target node lies in the right subtree of cur
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// Target node is in cur's left subtree
|
||||
// The target node lies in the left subtree of cur
|
||||
else if (cur.val > num) cur = cur.left;
|
||||
// Found target node, exit loop
|
||||
// The target node was found; exit the loop
|
||||
else break;
|
||||
}
|
||||
// Return target node
|
||||
// Return the target node
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
insert(num) {
|
||||
// If tree is empty, initialize root node
|
||||
// If the tree is empty, initialize the root node
|
||||
if (this.root === null) {
|
||||
this.root = new TreeNode(num);
|
||||
return;
|
||||
}
|
||||
let cur = this.root,
|
||||
pre = null;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Search in a loop until reaching a null reference beyond a leaf
|
||||
while (cur !== null) {
|
||||
// Found duplicate node, return directly
|
||||
// Return immediately if a duplicate node is found
|
||||
if (cur.val === num) return;
|
||||
pre = cur;
|
||||
// Insertion position is in cur's right subtree
|
||||
// The insertion position lies in the right subtree of cur
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// Insertion position is in cur's left subtree
|
||||
// The insertion position lies in the left subtree of cur
|
||||
else cur = cur.left;
|
||||
}
|
||||
// Insert node
|
||||
// Insert a node
|
||||
const node = new TreeNode(num);
|
||||
if (pre.val < num) pre.right = node;
|
||||
else pre.left = node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
remove(num) {
|
||||
// If tree is empty, return directly
|
||||
// Return immediately if the tree is empty
|
||||
if (this.root === null) return;
|
||||
let cur = this.root,
|
||||
pre = null;
|
||||
// Loop search, exit after passing leaf node
|
||||
// Search in a loop until reaching a null reference beyond a leaf
|
||||
while (cur !== null) {
|
||||
// Found node to delete, exit loop
|
||||
// The node to remove was found; exit the loop
|
||||
if (cur.val === num) break;
|
||||
pre = cur;
|
||||
// Node to delete is in cur's right subtree
|
||||
// The node to remove lies in the right subtree of cur
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// Node to delete is in cur's left subtree
|
||||
// The node to remove lies in the left subtree of cur
|
||||
else cur = cur.left;
|
||||
}
|
||||
// If no node to delete, return directly
|
||||
// Return immediately if the node to remove does not exist
|
||||
if (cur === null) return;
|
||||
// Number of child nodes = 0 or 1
|
||||
// Number of children = 0 or 1
|
||||
if (cur.left === null || cur.right === null) {
|
||||
// When number of child nodes = 0 / 1, child = null / that child node
|
||||
// With 0 / 1 children, child is null / the child node, respectively
|
||||
const child = cur.left !== null ? cur.left : cur.right;
|
||||
// Delete node cur
|
||||
// Remove node cur
|
||||
if (cur !== this.root) {
|
||||
if (pre.left === cur) pre.left = child;
|
||||
else pre.right = child;
|
||||
} else {
|
||||
// If deleted node is root node, reassign root node
|
||||
// If the removed node is the root, assign the new root
|
||||
this.root = child;
|
||||
}
|
||||
}
|
||||
// Number of child nodes = 2
|
||||
// Number of children = 2
|
||||
else {
|
||||
// Get next node of cur in inorder traversal
|
||||
// Get the inorder successor of cur
|
||||
let tmp = cur.right;
|
||||
while (tmp.left !== null) {
|
||||
tmp = tmp.left;
|
||||
}
|
||||
// Recursively delete node tmp
|
||||
// Recursively remove node tmp
|
||||
this.remove(tmp.val);
|
||||
// Replace cur with tmp
|
||||
// Replace the value of cur with the value of tmp
|
||||
cur.val = tmp.val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize binary search tree */
|
||||
/* Driver code */
|
||||
/* Initialize the binary search tree */
|
||||
const bst = new BinarySearchTree();
|
||||
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
// Different insertion orders produce different binary trees; this sequence produces a perfect binary tree
|
||||
const nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
|
||||
for (const num of nums) {
|
||||
bst.insert(num);
|
||||
}
|
||||
console.log('\nInitialized binary tree is\n');
|
||||
console.log('\nThe initialized binary tree is:\n');
|
||||
printTree(bst.getRoot());
|
||||
|
||||
/* Search node */
|
||||
/* Find a node */
|
||||
const node = bst.search(7);
|
||||
console.log('\nFound node object is ' + node + ', node value = ' + node.val);
|
||||
console.log('\nFound node object: ' + node + ', node value = ' + node.val);
|
||||
|
||||
/* Insert node */
|
||||
/* Insert a node */
|
||||
bst.insert(16);
|
||||
console.log('\nAfter inserting node 16, binary tree is\n');
|
||||
console.log('\nBinary tree after inserting node 16:\n');
|
||||
printTree(bst.getRoot());
|
||||
|
||||
/* Remove node */
|
||||
/* Remove a node */
|
||||
bst.remove(1);
|
||||
console.log('\nAfter removing node 1, binary tree is\n');
|
||||
console.log('\nBinary tree after removing node 1:\n');
|
||||
printTree(bst.getRoot());
|
||||
bst.remove(2);
|
||||
console.log('\nAfter removing node 2, binary tree is\n');
|
||||
console.log('\nBinary tree after removing node 2:\n');
|
||||
printTree(bst.getRoot());
|
||||
bst.remove(4);
|
||||
console.log('\nAfter removing node 4, binary tree is\n');
|
||||
console.log('\nBinary tree after removing node 4:\n');
|
||||
printTree(bst.getRoot());
|
||||
|
||||
@@ -7,29 +7,29 @@
|
||||
const { TreeNode } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Initialize binary tree */
|
||||
// Initialize nodes
|
||||
/* Initialize the binary tree */
|
||||
// Initialize the nodes
|
||||
let n1 = new TreeNode(1),
|
||||
n2 = new TreeNode(2),
|
||||
n3 = new TreeNode(3),
|
||||
n4 = new TreeNode(4),
|
||||
n5 = new TreeNode(5);
|
||||
// Build references (pointers) between nodes
|
||||
// Set up references (pointers) between the nodes
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
console.log('\nInitialize binary tree\n');
|
||||
console.log('\nInitialize the binary tree\n');
|
||||
printTree(n1);
|
||||
|
||||
/* Insert node P between n1 -> n2 */
|
||||
/* Insert and remove nodes */
|
||||
const P = new TreeNode(0);
|
||||
// Delete node
|
||||
// Insert node P between n1 and n2 in n1 -> n2
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
console.log('\nAfter inserting node P\n');
|
||||
console.log('\nAfter inserting node P:\n');
|
||||
printTree(n1);
|
||||
// Remove node P
|
||||
n1.left = n2;
|
||||
console.log('\nAfter removing node P\n');
|
||||
console.log('\nAfter removing node P:\n');
|
||||
printTree(n1);
|
||||
|
||||
@@ -9,26 +9,26 @@ const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* Level-order traversal */
|
||||
function levelOrder(root) {
|
||||
// Initialize queue, add root node
|
||||
// Initialize a queue and enqueue the root
|
||||
const queue = [root];
|
||||
// Initialize a list to save the traversal sequence
|
||||
// Initialize a list to store the traversal sequence
|
||||
const list = [];
|
||||
while (queue.length) {
|
||||
let node = queue.shift(); // Dequeue
|
||||
list.push(node.val); // Save node value
|
||||
if (node.left) queue.push(node.left); // Left child node enqueue
|
||||
if (node.right) queue.push(node.right); // Right child node enqueue
|
||||
let node = queue.shift(); // Dequeue from the queue
|
||||
list.push(node.val); // Store the node value
|
||||
if (node.left) queue.push(node.left); // Enqueue the left child
|
||||
if (node.right) queue.push(node.right); // Enqueue the right child
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
/* Driver code */
|
||||
/* Initialize the binary tree */
|
||||
// Use a helper function that builds a binary tree directly from an array
|
||||
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree\n');
|
||||
console.log('\nInitialize the binary tree\n');
|
||||
printTree(root);
|
||||
|
||||
/* Level-order traversal */
|
||||
const list = levelOrder(root);
|
||||
console.log('\nLevel-order traversal node print sequence = ' + list);
|
||||
console.log('\nNode sequence from level-order traversal = ' + list);
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
// Initialize list for storing traversal sequence
|
||||
// Initialize a list to store the traversal sequence
|
||||
const list = [];
|
||||
|
||||
/* Preorder traversal */
|
||||
function preOrder(root) {
|
||||
if (root === null) return;
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
// Visit order: root -> left subtree -> right subtree
|
||||
list.push(root.val);
|
||||
preOrder(root.left);
|
||||
preOrder(root.right);
|
||||
@@ -22,7 +22,7 @@ function preOrder(root) {
|
||||
/* Inorder traversal */
|
||||
function inOrder(root) {
|
||||
if (root === null) return;
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
// Visit order: left subtree -> root -> right subtree
|
||||
inOrder(root.left);
|
||||
list.push(root.val);
|
||||
inOrder(root.right);
|
||||
@@ -31,30 +31,30 @@ function inOrder(root) {
|
||||
/* Postorder traversal */
|
||||
function postOrder(root) {
|
||||
if (root === null) return;
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
// Visit order: left subtree -> right subtree -> root
|
||||
postOrder(root.left);
|
||||
postOrder(root.right);
|
||||
list.push(root.val);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
/* Driver code */
|
||||
/* Initialize the binary tree */
|
||||
// Use a helper function that builds a binary tree directly from an array
|
||||
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree\n');
|
||||
console.log('\nInitialize the binary tree\n');
|
||||
printTree(root);
|
||||
|
||||
/* Preorder traversal */
|
||||
list.length = 0;
|
||||
preOrder(root);
|
||||
console.log('\nPreorder traversal node print sequence = ' + list);
|
||||
console.log('\nNode sequence from preorder traversal = ' + list);
|
||||
|
||||
/* Inorder traversal */
|
||||
list.length = 0;
|
||||
inOrder(root);
|
||||
console.log('\nInorder traversal node print sequence = ' + list);
|
||||
console.log('\nNode sequence from inorder traversal = ' + list);
|
||||
|
||||
/* Postorder traversal */
|
||||
list.length = 0;
|
||||
postOrder(root);
|
||||
console.log('\nPostorder traversal node print sequence = ' + list);
|
||||
console.log('\nNode sequence from postorder traversal = ' + list);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/* Linked list node */
|
||||
class ListNode {
|
||||
val; // Node value
|
||||
next; // Reference (pointer) to next node
|
||||
next; // Reference (pointer) to the next node
|
||||
constructor(val, next) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.next = next === undefined ? null : next;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
const { arrToTree } = require('./TreeNode');
|
||||
|
||||
/* Print linked list */
|
||||
/* Print a linked list */
|
||||
function printLinkedList(head) {
|
||||
let list = [];
|
||||
while (head !== null) {
|
||||
@@ -22,7 +22,7 @@ function Trunk(prev, str) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Print binary tree
|
||||
* Print the binary tree
|
||||
* This tree printer is borrowed from TECHIE DELIGHT
|
||||
* https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
*/
|
||||
@@ -30,7 +30,7 @@ function printTree(root) {
|
||||
printTree(root, null, false);
|
||||
}
|
||||
|
||||
/* Print binary tree */
|
||||
/* Print the binary tree */
|
||||
function printTree(root, prev, isRight) {
|
||||
if (root === null) {
|
||||
return;
|
||||
@@ -71,11 +71,11 @@ function showTrunks(p) {
|
||||
process.stdout.write(p.str);
|
||||
}
|
||||
|
||||
/* Print heap */
|
||||
/* Print a heap */
|
||||
function printHeap(arr) {
|
||||
console.log('Heap array representation:');
|
||||
console.log('Array representation of the heap:');
|
||||
console.log(arr);
|
||||
console.log('Heap tree representation:');
|
||||
console.log('Tree representation of the heap:');
|
||||
printTree(arrToTree(arr));
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
/* Binary tree node */
|
||||
class TreeNode {
|
||||
val; // Node value
|
||||
left; // Left child pointer
|
||||
right; // Right child pointer
|
||||
height; // Node height
|
||||
left; // Pointer to the left child
|
||||
right; // Pointer to the right child
|
||||
height; //Node height
|
||||
constructor(val, left, right, height) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.left = left === undefined ? null : left;
|
||||
@@ -18,7 +18,7 @@ class TreeNode {
|
||||
}
|
||||
}
|
||||
|
||||
/* Deserialize array to binary tree */
|
||||
/* Deserialize an array into a binary tree */
|
||||
function arrToTree(arr, i = 0) {
|
||||
if (i < 0 || i >= arr.length || arr[i] === null) {
|
||||
return null;
|
||||
|
||||
@@ -11,7 +11,7 @@ class Vertex {
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
/* Input value list vals, return vertex list vets */
|
||||
/* Given the list of values vals, return the list of vertices vets */
|
||||
static valsToVets(vals) {
|
||||
const vets = [];
|
||||
for (let i = 0; i < vals.length; i++) {
|
||||
@@ -20,7 +20,7 @@ class Vertex {
|
||||
return vets;
|
||||
}
|
||||
|
||||
/* Input vertex list vets, return value list vals */
|
||||
/* Given the list of vertices vets, return the list of values vals */
|
||||
static vetsToVals(vets) {
|
||||
const vals = [];
|
||||
for (const vet of vets) {
|
||||
|
||||
@@ -47,7 +47,7 @@ for (const result of results) {
|
||||
}
|
||||
|
||||
console.log(`Tested ${entries.length} files`);
|
||||
console.log(`Found exception in ${errors.length} files`);
|
||||
console.log(`Exceptions occurred in ${errors.length} files`);
|
||||
|
||||
if (errors.length) {
|
||||
console.log();
|
||||
|
||||
Reference in New Issue
Block a user