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:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -10,59 +10,59 @@ import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class array {
/* Random access to element */
/* Access an element at a random index */
static int randomAccess(int[] nums) {
// Randomly select a number in the interval [0, nums.length)
// Choose a random number in the interval [0, nums.length)
int randomIndex = ThreadLocalRandom.current().nextInt(0, nums.length);
// Retrieve and return the random element
// Get and return the randomly selected element
int randomNum = nums[randomIndex];
return randomNum;
}
/* Extend array length */
/* Extend the array length */
static int[] extend(int[] nums, int enlarge) {
// Initialize an array with extended length
// Initialize an array with the extended length
int[] res = new int[nums.length + enlarge];
// Copy all elements from the original array to the new array
for (int 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 */
static void insert(int[] nums, int num, int 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 (int 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` */
static void remove(int[] nums, int index) {
// Move all elements after index index forward by one position
// Shift all elements after index `index` one position to the left
for (int i = index; i < nums.length - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* Traverse array */
/* Traverse the array */
static void traverse(int[] nums) {
int count = 0;
// Traverse array by index
// Traverse the array by index
for (int i = 0; i < nums.length; i++) {
count += nums[i];
}
// Direct traversal of array elements
// Iterate directly over the array elements
for (int num : nums) {
count += num;
}
}
/* Find the specified element in the array */
/* Find a specified element in the array */
static int find(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target)
@@ -71,35 +71,35 @@ public class array {
return -1;
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
/* Initialize array */
/* Initialize the array */
int[] arr = new int[5];
System.out.println("Array arr = " + Arrays.toString(arr));
int[] nums = { 1, 3, 2, 5, 4 };
System.out.println("Array nums = " + Arrays.toString(nums));
/* Insert element */
/* Random access */
int randomNum = randomAccess(nums);
System.out.println("Get random element in nums " + randomNum);
System.out.println("Randomly selected element from nums: " + randomNum);
/* Traverse array */
/* Extend the length */
nums = extend(nums, 3);
System.out.println("Extend array length to 8, resulting in nums = " + Arrays.toString(nums));
System.out.println("Extend the array length to 8, giving nums = " + Arrays.toString(nums));
/* Insert element */
/* Insert an element */
insert(nums, 6, 3);
System.out.println("Insert number 6 at index 3, resulting in nums = " + Arrays.toString(nums));
System.out.println("Insert the number 6 at index 3, giving nums = " + Arrays.toString(nums));
/* Remove element */
/* Remove an element */
remove(nums, 2);
System.out.println("Remove element at index 2, resulting in nums = " + Arrays.toString(nums));
System.out.println("Remove the element at index 2, giving nums = " + Arrays.toString(nums));
/* Traverse array */
/* Traverse the array */
traverse(nums);
/* Find element */
/* Find an element */
int index = find(nums, 3);
System.out.println("Find element 3 in nums, get index = " + index);
System.out.println("Find element 3 in nums, giving index = " + index);
}
}

View File

@@ -26,7 +26,7 @@ public class linked_list {
n0.next = n1;
}
/* Access the node at index index in the linked list */
/* Access the node at index `index` in the linked list */
static ListNode access(ListNode head, int index) {
for (int i = 0; i < index; i++) {
if (head == null)
@@ -48,39 +48,39 @@ public class linked_list {
return -1;
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
/* Initialize linked list */
// Initialize each node
/* Initialize the linked list */
// Initialize the individual nodes
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(5);
ListNode 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;
System.out.println("Initialized linked list is");
System.out.println("The initialized linked list is");
PrintUtil.printLinkedList(n0);
/* Insert node */
/* Insert a node */
insert(n0, new ListNode(0));
System.out.println("Linked list after inserting node is");
System.out.println("The linked list after inserting a node is");
PrintUtil.printLinkedList(n0);
/* Remove node */
/* Remove a node */
remove(n0);
System.out.println("Linked list after removing node is");
System.out.println("The linked list after removing a node is");
PrintUtil.printLinkedList(n0);
/* Access node */
/* Access a node */
ListNode node = access(n0, 3);
System.out.println("Value of node at index 3 in linked list = " + node.val);
System.out.println("Value of the node at index 3 in the linked list = " + node.val);
/* Search node */
/* Find a node */
int index = find(n0, 2);
System.out.println("Index of node with value 2 in linked list = " + index);
System.out.println("Index of the node with value 2 in the linked list = " + index);
}
}

View File

@@ -10,25 +10,25 @@ import java.util.*;
public class list {
public static void main(String[] args) {
/* Initialize list */
// Note that the array element type is Integer[], the wrapper class of int[]
/* Initialize the list */
// Use Integer[]: Integer is the wrapper type for int
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("List nums = " + nums);
/* Update element */
/* Access an element */
int num = nums.get(1);
System.out.println("Access element at index 1, get num = " + num);
System.out.println("Access the element at index 1, giving num = " + num);
/* Add elements at the end */
/* Update an element */
nums.set(1, 0);
System.out.println("Update element at index 1 to 0, resulting in nums = " + nums);
System.out.println("Update the element at index 1 to 0, giving nums = " + nums);
/* Remove element */
/* Clear the list */
nums.clear();
System.out.println("After clearing list, nums = " + nums);
System.out.println("After clearing the list, nums = " + nums);
/* Direct traversal of list elements */
/* Append at the end */
nums.add(1);
nums.add(3);
nums.add(2);
@@ -36,20 +36,20 @@ public class list {
nums.add(4);
System.out.println("After adding elements, nums = " + nums);
/* Sort list */
/* Insert an element in the middle */
nums.add(3, 6);
System.out.println("Insert number 6 at index 3, resulting in nums = " + nums);
System.out.println("Insert the number 6 at index 3, giving nums = " + nums);
/* Remove element */
/* Remove an element */
nums.remove(3);
System.out.println("Remove element at index 3, resulting in nums = " + nums);
System.out.println("Remove the element at index 3, giving nums = " + nums);
/* Traverse list by index */
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* Directly traverse list elements */
/* Iterate directly over the list elements */
for (int x : nums) {
count += x;
}
@@ -57,10 +57,10 @@ public class list {
/* Concatenate two lists */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1);
System.out.println("Concatenate list nums1 to nums, resulting in nums = " + nums);
System.out.println("After appending list nums1 to nums, nums = " + nums);
/* Sort list */
/* Sort the list */
Collections.sort(nums);
System.out.println("After sorting list, nums = " + nums);
System.out.println("After sorting the list, nums = " + nums);
}
}

View File

@@ -10,44 +10,44 @@ import java.util.*;
/* List class */
class MyList {
private int[] arr; // Array (stores list elements)
private int[] arr; // Array (stores the list elements)
private int capacity = 10; // List capacity
private int size = 0; // List length (current number of elements)
private int extendRatio = 2; // Multiple by which the list capacity is extended each time
private int extendRatio = 2; // Factor by which the list capacity grows each time
/* Constructor */
public MyList() {
arr = new int[capacity];
}
/* Get list length (current number of elements) */
/* Get the list length (current number of elements) */
public int size() {
return size;
}
/* Get list capacity */
/* Get the list capacity */
public int capacity() {
return capacity;
}
/* Update element */
/* Access an element */
public int get(int 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 >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
return arr[index];
}
/* Add elements at the end */
/* Update an element */
public void set(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
arr[index] = num;
}
/* Direct traversal of list elements */
/* Append at the end */
public void add(int num) {
// When the number of elements exceeds capacity, trigger the extension mechanism
// Grow the capacity when adding an element would exceed it
if (size == capacity())
extendCapacity();
arr[size] = num;
@@ -55,14 +55,14 @@ class MyList {
size++;
}
/* Sort list */
/* Insert an element in the middle */
public void insert(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("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 (size == capacity())
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 (int j = size - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
@@ -71,12 +71,12 @@ class MyList {
size++;
}
/* Remove element */
/* Remove an element */
public int remove(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
int num = arr[index];
// Move all elements after index forward by one position
// Shift all elements after index `index` one position to the left
for (int j = index; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
@@ -86,18 +86,18 @@ class MyList {
return num;
}
/* Driver Code */
/* Grow the list capacity */
public void 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 as long as the original and copy the original array into it
arr = Arrays.copyOf(arr, capacity() * extendRatio);
// Add elements at the end
// Update the list capacity
capacity = arr.length;
}
/* Convert list to array */
/* Convert the list to an array */
public int[] toArray() {
int size = size();
// Elements enqueue
// Convert only the list elements within the occupied range
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = get(i);
@@ -107,41 +107,41 @@ class MyList {
}
public class my_list {
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
/* Initialize list */
/* Initialize the list */
MyList nums = new MyList();
/* Direct traversal of list elements */
/* Append at the end */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
System.out.println("List nums = " + Arrays.toString(nums.toArray()) +
", capacity = " + nums.capacity() + ", length = " + nums.size());
" , capacity = " + nums.capacity() + " , size = " + nums.size());
/* Sort list */
/* Insert an element in the middle */
nums.insert(3, 6);
System.out.println("Insert number 6 at index 3, resulting in nums = " + Arrays.toString(nums.toArray()));
System.out.println("Insert the number 6 at index 3, giving nums = " + Arrays.toString(nums.toArray()));
/* Remove element */
/* Remove an element */
nums.remove(3);
System.out.println("Remove element at index 3, resulting in nums = " + Arrays.toString(nums.toArray()));
System.out.println("Remove the element at index 3, giving nums = " + Arrays.toString(nums.toArray()));
/* Update element */
/* Access an element */
int num = nums.get(1);
System.out.println("Access element at index 1, get num = " + num);
System.out.println("Access the element at index 1, giving num = " + num);
/* Add elements at the end */
/* Update an element */
nums.set(1, 0);
System.out.println("Update element at index 1 to 0, resulting in nums = " + Arrays.toString(nums.toArray()));
System.out.println("Update the element at index 1 to 0, giving nums = " + Arrays.toString(nums.toArray()));
/* Test capacity expansion mechanism */
/* Test capacity growth */
for (int 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);
}
System.out.println("List nums after expansion = " + Arrays.toString(nums.toArray()) +
", capacity = " + nums.capacity() + ", length = " + nums.size());
System.out.println("After expansion, list nums = " + Arrays.toString(nums.toArray()) +
" , capacity = " + nums.capacity() + " , size = " + nums.size());
}
}

View File

@@ -9,10 +9,10 @@ package chapter_backtracking;
import java.util.*;
public class n_queens {
/* Backtracking algorithm: N queens */
/* Backtracking: n-queens */
public static void backtrack(int row, int n, List<List<String>> state, List<List<List<String>>> res,
boolean[] cols, boolean[] diags1, boolean[] diags2) {
// When all rows are placed, record the solution
// Record a solution when a queen has been placed in every row
if (row == n) {
List<List<String>> copyState = new ArrayList<>();
for (List<String> sRow : state) {
@@ -21,28 +21,28 @@ public class n_queens {
res.add(copyState);
return;
}
// Traverse all columns
// Iterate over all columns
for (int 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
int diag1 = row - col + n - 1;
int 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.get(row).set(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.get(row).set(col, "#");
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* Solve N queens */
/* Solve the n-queens problem */
public static List<List<List<String>>> nQueens(int 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
List<List<String>> state = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<String> row = new ArrayList<>();
@@ -51,9 +51,9 @@ public class n_queens {
}
state.add(row);
}
boolean[] cols = new boolean[n]; // Record whether there is a queen in the column
boolean[] diags1 = new boolean[2 * n - 1]; // Record whether there is a queen on the main diagonal
boolean[] diags2 = new boolean[2 * n - 1]; // Record whether there is a queen on the anti-diagonal
boolean[] cols = new boolean[n]; // Track whether a column contains a queen
boolean[] diags1 = new boolean[2 * n - 1]; // Track whether a main diagonal contains a queen
boolean[] diags2 = new boolean[2 * n - 1]; // Track whether an anti-diagonal contains a queen
List<List<List<String>>> res = new ArrayList<>();
backtrack(0, n, state, res, cols, diags1, diags2);
@@ -65,8 +65,8 @@ public class n_queens {
int n = 4;
List<List<List<String>>> res = nQueens(n);
System.out.println("Input board size is " + n);
System.out.println("Total queen placement solutions: " + res.size() + "");
System.out.println("Input board side length: " + n);
System.out.println("There are " + res.size() + " queen placements");
for (List<List<String>> state : res) {
System.out.println("--------------------");
for (List<String> row : state) {

View File

@@ -9,24 +9,24 @@ package chapter_backtracking;
import java.util.*;
public class permutations_i {
/* Backtracking algorithm: Permutations I */
/* Backtracking: permutations I */
public static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> 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.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// Traverse all choices
// Iterate over all choices
for (int i = 0; i < choices.length; i++) {
int choice = choices[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.add(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.remove(state.size() - 1);
}
@@ -46,6 +46,6 @@ public class permutations_i {
List<List<Integer>> res = permutationsI(nums);
System.out.println("Input array nums = " + Arrays.toString(nums));
System.out.println("All permutations res = " + res);
System.out.println("All permutations: res = " + res);
}
}

View File

@@ -9,26 +9,26 @@ package chapter_backtracking;
import java.util.*;
public class permutations_ii {
/* Backtracking algorithm: Permutations II */
/* Backtracking: permutations II */
static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> 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.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// Traverse all choices
// Iterate over all choices
Set<Integer> duplicated = new HashSet<Integer>();
for (int i = 0; i < choices.length; i++) {
int choice = choices[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.contains(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.add(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.remove(state.size() - 1);
}
@@ -48,6 +48,6 @@ public class permutations_ii {
List<List<Integer>> res = permutationsII(nums);
System.out.println("Input array nums = " + Arrays.toString(nums));
System.out.println("All permutations res = " + res);
System.out.println("All permutations: res = " + res);
}
}

View File

@@ -12,13 +12,13 @@ import java.util.*;
public class preorder_traversal_i_compact {
static List<TreeNode> res;
/* Preorder traversal: Example 1 */
/* Preorder traversal: example 1 */
static void preOrder(TreeNode root) {
if (root == null) {
return;
}
if (root.val == 7) {
// Record solution
// Record the solution
res.add(root);
}
preOrder(root.left);
@@ -27,7 +27,7 @@ public class preorder_traversal_i_compact {
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree");
System.out.println("\nInitialize the binary tree");
PrintUtil.printTree(root);
// Preorder traversal

View File

@@ -13,15 +13,15 @@ public class preorder_traversal_ii_compact {
static List<TreeNode> path;
static List<List<TreeNode>> res;
/* Preorder traversal: Example 2 */
/* Preorder traversal: example 2 */
static void preOrder(TreeNode root) {
if (root == null) {
return;
}
// Attempt
// Try
path.add(root);
if (root.val == 7) {
// Record solution
// Record the solution
res.add(new ArrayList<>(path));
}
preOrder(root.left);
@@ -32,7 +32,7 @@ public class preorder_traversal_ii_compact {
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree");
System.out.println("\nInitialize the binary tree");
PrintUtil.printTree(root);
// Preorder traversal
@@ -40,7 +40,7 @@ public class preorder_traversal_ii_compact {
res = new ArrayList<>();
preOrder(root);
System.out.println("\nOutput all paths from root node to node 7");
System.out.println("\nOutput all paths from the root to nodes with value 7");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {

View File

@@ -13,16 +13,16 @@ public class preorder_traversal_iii_compact {
static List<TreeNode> path;
static List<List<TreeNode>> res;
/* Preorder traversal: Example 3 */
/* Preorder traversal: example 3 */
static void preOrder(TreeNode root) {
// Pruning
// Prune
if (root == null || root.val == 3) {
return;
}
// Attempt
// Try
path.add(root);
if (root.val == 7) {
// Record solution
// Record the solution
res.add(new ArrayList<>(path));
}
preOrder(root.left);
@@ -33,7 +33,7 @@ public class preorder_traversal_iii_compact {
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree");
System.out.println("\nInitialize the binary tree");
PrintUtil.printTree(root);
// Preorder traversal
@@ -41,7 +41,7 @@ public class preorder_traversal_iii_compact {
res = new ArrayList<>();
preOrder(root);
System.out.println("\nOutput all paths from root node to node 7, paths do not include nodes with value 3");
System.out.println("\nOutput all paths from the root to nodes with value 7 that contain no node with value 3");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {

View File

@@ -10,47 +10,47 @@ import utils.*;
import java.util.*;
public class preorder_traversal_iii_template {
/* Check if the current state is a solution */
/* Check whether the current state is a solution */
static boolean isSolution(List<TreeNode> state) {
return !state.isEmpty() && state.get(state.size() - 1).val == 7;
}
/* Record solution */
/* Record the solution */
static void recordSolution(List<TreeNode> state, List<List<TreeNode>> res) {
res.add(new ArrayList<>(state));
}
/* Check if the choice is valid under the current state */
/* Check whether the choice is valid in the current state */
static boolean isValid(List<TreeNode> state, TreeNode choice) {
return choice != null && choice.val != 3;
}
/* Update state */
/* Update the state */
static void makeChoice(List<TreeNode> state, TreeNode choice) {
state.add(choice);
}
/* Restore state */
/* Restore the state */
static void undoChoice(List<TreeNode> state, TreeNode choice) {
state.remove(state.size() - 1);
}
/* Backtracking algorithm: Example 3 */
/* Backtracking: example 3 */
static void backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> 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 (TreeNode choice : 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, Arrays.asList(choice.left, choice.right), res);
// Backtrack: undo choice, restore to previous state
// Backtrack: undo the choice and restore the previous state
undoChoice(state, choice);
}
}
@@ -58,14 +58,14 @@ public class preorder_traversal_iii_template {
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree");
System.out.println("\nInitialize the binary tree");
PrintUtil.printTree(root);
// Backtracking algorithm
List<List<TreeNode>> res = new ArrayList<>();
backtrack(new ArrayList<>(), Arrays.asList(root), res);
System.out.println("\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3");
System.out.println("\nOutput all paths from the root to nodes with value 7, requiring that no node on the path has value 3");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {

View File

@@ -9,26 +9,26 @@ package chapter_backtracking;
import java.util.*;
public class subset_sum_i {
/* Backtracking algorithm: Subset sum I */
/* Backtracking: subset sum I */
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// When the subset sum equals target, record the solution
// Record a solution when the remaining target is zero, so the subset sums to the original target
if (target == 0) {
res.add(new ArrayList<>(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 (int 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 element exceeds the remaining target
// The array is sorted, so later elements are at least as large and 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.add(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.remove(state.size() - 1);
}
}
@@ -37,8 +37,8 @@ public class subset_sum_i {
static List<List<Integer>> subsetSumI(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // State (subset)
Arrays.sort(nums); // Sort nums
int start = 0; // Start point for traversal
List<List<Integer>> res = new ArrayList<>(); // Result list (subset list)
int start = 0; // Starting index for iteration
List<List<Integer>> res = new ArrayList<>(); // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
@@ -50,6 +50,6 @@ public class subset_sum_i {
List<List<Integer>> res = subsetSumI(nums, target);
System.out.println("Input array nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("All subsets with sum equal to " + target + " are res = " + res);
System.out.println("All subsets with sum " + target + " : res = " + res);
}
}

View File

@@ -9,33 +9,33 @@ package chapter_backtracking;
import java.util.*;
public class subset_sum_i_naive {
/* Backtracking algorithm: Subset sum I */
/* Backtracking: subset sum I */
static void backtrack(List<Integer> state, int target, int total, int[] choices, List<List<Integer>> res) {
// When the subset sum equals target, record the solution
// Record a solution when the subset sum equals target
if (total == target) {
res.add(new ArrayList<>(state));
return;
}
// Traverse all choices
// Iterate over all choices
for (int 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.add(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.remove(state.size() - 1);
}
}
/* Solve subset sum I (including duplicate subsets) */
/* Solve subset sum I (with duplicate subsets) */
static List<List<Integer>> subsetSumINaive(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // State (subset)
int total = 0; // Subset sum
List<List<Integer>> res = new ArrayList<>(); // Result list (subset list)
List<List<Integer>> res = new ArrayList<>(); // Result list (list of subsets)
backtrack(state, target, total, nums, res);
return res;
}
@@ -47,7 +47,7 @@ public class subset_sum_i_naive {
List<List<Integer>> res = subsetSumINaive(nums, target);
System.out.println("Input array nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("All subsets with sum equal to " + target + " are res = " + res);
System.out.println("Please note that this method outputs results containing duplicate sets");
System.out.println("All subsets with sum " + target + " : res = " + res);
System.out.println("Note that this method produces duplicate subsets");
}
}

View File

@@ -9,31 +9,31 @@ package chapter_backtracking;
import java.util.*;
public class subset_sum_ii {
/* Backtracking algorithm: Subset sum II */
/* Backtracking: subset sum II */
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// When the subset sum equals target, record the solution
// Record a solution when the remaining target is zero, so the subset sums to the original target
if (target == 0) {
res.add(new ArrayList<>(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: iterate from start to avoid choosing the same element again
for (int 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 element exceeds the remaining target
// The array is sorted, so later elements are at least as large and 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.add(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.remove(state.size() - 1);
}
}
@@ -42,8 +42,8 @@ public class subset_sum_ii {
static List<List<Integer>> subsetSumII(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // State (subset)
Arrays.sort(nums); // Sort nums
int start = 0; // Start point for traversal
List<List<Integer>> res = new ArrayList<>(); // Result list (subset list)
int start = 0; // Starting index for iteration
List<List<Integer>> res = new ArrayList<>(); // Result list (list of subsets)
backtrack(state, target, nums, start, res);
return res;
}
@@ -55,6 +55,6 @@ public class subset_sum_ii {
List<List<Integer>> res = subsetSumII(nums, target);
System.out.println("Input array nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("All subsets with sum equal to " + target + " are res = " + res);
System.out.println("All subsets with sum " + target + " : res = " + res);
}
}

View File

@@ -7,7 +7,7 @@
package chapter_computational_complexity;
public class complexity_exercises {
/* Iterative summation */
/* Sum using iteration */
static int sumIter(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
@@ -16,7 +16,7 @@ public class complexity_exercises {
return res;
}
/* Recursive summation */
/* Sum using recursion */
static int sumRecur(int n) {
if (n == 1) {
return 1;
@@ -24,7 +24,7 @@ public class complexity_exercises {
return n + sumRecur(n - 1);
}
/* Linear loop */
/* Linear-time loop */
static int linearLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
@@ -33,7 +33,7 @@ public class complexity_exercises {
return res;
}
/* Quadratic loop */
/* Quadratic-time loop */
static int quadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
@@ -44,7 +44,7 @@ public class complexity_exercises {
return res;
}
/* Logarithmic loop */
/* Logarithmic-time loop */
static int logarithmicLoop(int n) {
while (n > 1) {
n /= 2;

View File

@@ -10,7 +10,7 @@ public class iteration {
/* for loop */
static int forLoop(int n) {
int res = 0;
// Sum 1, 2, ..., n-1, n
// Sum 1, 2, ..., n-1, n in a loop
for (int i = 1; i <= n; i++) {
res += i;
}
@@ -20,11 +20,11 @@ public class iteration {
/* while loop */
static int whileLoop(int n) {
int res = 0;
int i = 1; // Initialize condition variable
// Sum 1, 2, ..., n-1, n
int 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;
}
@@ -32,23 +32,23 @@ public class iteration {
/* while loop (two updates) */
static int whileLoopII(int n) {
int res = 0;
int i = 1; // Initialize condition variable
// Sum 1, 4, 10, ...
int 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 */
static String nestedForLoop(int n) {
StringBuilder res = new StringBuilder();
// Loop i = 1, 2, ..., n-1, n
// Loop over i = 1, 2, ..., n-1, n
for (int i = 1; i <= n; i++) {
// Loop j = 1, 2, ..., n-1, n
// Loop over j = 1, 2, ..., n-1, n
for (int j = 1; j <= n; j++) {
res.append("(" + i + ", " + j + "), ");
}
@@ -56,21 +56,21 @@ public class iteration {
return res.toString();
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
int n = 5;
int res;
res = forLoop(n);
System.out.println("\nfor loop sum result res = " + res);
System.out.println("\nSum from the for loop: res = " + res);
res = whileLoop(n);
System.out.println("\nwhile loop sum result res = " + res);
System.out.println("\nSum from the while loop: res = " + res);
res = whileLoopII(n);
System.out.println("\nwhile loop (two updates) sum result res = " + res);
System.out.println("\nSum from the while loop (two updates): res = " + res);
String resStr = nestedForLoop(n);
System.out.println("\nDouble for loop traversal result " + resStr);
System.out.println("\nTraversal result from the nested for loops: " + resStr);
}
}

View File

@@ -11,12 +11,12 @@ import java.util.Stack;
public class recursion {
/* Recursion */
static int recur(int n) {
// Termination condition
// Base case
if (n == 1)
return 1;
// Recurse: recursive call
// Recurse: make a recursive call
int res = recur(n - 1);
// Return: return result
// Unwind: return the result
return n + res;
}
@@ -25,14 +25,14 @@ public class recursion {
// Use an explicit stack to simulate the system call stack
Stack<Integer> stack = new Stack<>();
int res = 0;
// Recurse: recursive call
// Recurse: make a recursive call
for (int 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.isEmpty()) {
// Simulate "return" with "pop"
// Simulate unwinding by popping from the stack
res += stack.pop();
}
// res = 1+2+3+...+n
@@ -41,39 +41,39 @@ public class recursion {
/* Tail recursion */
static int tailRecur(int n, int 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 */
static int fib(int 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)
int res = fib(n - 1) + fib(n - 2);
// Return result f(n)
// Return the result f(n)
return res;
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
int n = 5;
int res;
res = recur(n);
System.out.println("\nRecursive function sum result res = " + res);
System.out.println("\nSum from recursion: res = " + res);
res = forLoopRecur(n);
System.out.println("\nUsing iteration to simulate recursive sum result res = " + res);
System.out.println("\nSum from simulating recursion with iteration: res = " + res);
res = tailRecur(n, 0);
System.out.println("\nTail recursive function sum result res = " + res);
System.out.println("\nSum from tail recursion: res = " + res);
res = fib(n);
System.out.println("\nThe " + n + "th term of the Fibonacci sequence is " + res);
System.out.println("\nFibonacci term " + n + " is " + res);
}
}

View File

@@ -16,9 +16,9 @@ public class space_complexity {
return 0;
}
/* Constant order */
/* Constant complexity */
static void constant(int n) {
// Constants, variables, objects occupy O(1) space
// Constants, variables, and objects occupy O(1) space
final int a = 0;
int b = 0;
int[] nums = new int[10000];
@@ -27,41 +27,41 @@ public class space_complexity {
for (int i = 0; i < n; i++) {
int c = 0;
}
// Functions in the loop occupy O(1) space
// Function calls in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
function();
}
}
/* Linear order */
/* Linear complexity */
static void linear(int n) {
// Array of length n uses O(n) space
// An array of length n uses O(n) space
int[] nums = new int[n];
// A list of length n occupies O(n) space
List<ListNode> nodes = new ArrayList<>();
for (int i = 0; i < n; i++) {
nodes.add(new ListNode(i));
}
// A hash table of length n occupies O(n) space
// A hash table with n entries occupies O(n) space
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(i, String.valueOf(i));
}
}
/* Linear order (recursive implementation) */
/* Linear complexity (recursive implementation) */
static void linearRecur(int n) {
System.out.println("Recursion n = " + n);
System.out.println("Recursive call: n = " + n);
if (n == 1)
return;
linearRecur(n - 1);
}
/* Exponential order */
/* Quadratic complexity */
static void quadratic(int n) {
// Matrix uses O(n^2) space
// The matrix uses O(n^2) space
int[][] numMatrix = new int[n][n];
// 2D list uses O(n^2) space
// The two-dimensional list occupies O(n^2) space
List<List<Integer>> numList = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> tmp = new ArrayList<>();
@@ -72,17 +72,17 @@ public class space_complexity {
}
}
/* Quadratic order (recursive implementation) */
/* Quadratic complexity (recursive implementation) */
static int quadraticRecur(int n) {
if (n <= 0)
return 0;
// Array nums has length n, n-1, ..., 2, 1
// The lengths of array nums are n, n-1, ..., 2, 1
int[] nums = new int[n];
System.out.println("In recursion n = " + n + ", nums length = " + nums.length);
System.out.println("Recursive call: n = " + n + " with nums length = " + nums.length);
return quadraticRecur(n - 1);
}
/* Driver Code */
/* Exponential complexity (building a perfect binary tree) */
static TreeNode buildTree(int n) {
if (n == 0)
return null;
@@ -92,18 +92,18 @@ public class space_complexity {
return root;
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
int 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
TreeNode root = buildTree(n);
PrintUtil.printTree(root);
}

View File

@@ -7,7 +7,7 @@
package chapter_computational_complexity;
public class time_complexity {
/* Constant order */
/* Constant complexity */
static int constant(int n) {
int count = 0;
int size = 100000;
@@ -16,7 +16,7 @@ public class time_complexity {
return count;
}
/* Linear order */
/* Linear complexity */
static int linear(int n) {
int count = 0;
for (int i = 0; i < n; i++)
@@ -24,20 +24,20 @@ public class time_complexity {
return count;
}
/* Linear order (traversing array) */
/* Linear complexity (array traversal) */
static int arrayTraversal(int[] nums) {
int count = 0;
// Number of iterations is proportional to the array length
// The number of iterations is proportional to the array length
for (int num : nums) {
count++;
}
return count;
}
/* Exponential order */
/* Quadratic complexity */
static int quadratic(int n) {
int 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 (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
count++;
@@ -46,29 +46,29 @@ public class time_complexity {
return count;
}
/* Quadratic order (bubble sort) */
/* Quadratic complexity (bubble sort) */
static int bubbleSort(int[] nums) {
int count = 0; // Counter
// Outer loop: unsorted range is [0, i]
// Outer loop: the unsorted range is [0, i]
for (int 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 (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int 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) */
static int exponential(int n) {
int 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 (int i = 0; i < n; i++) {
for (int j = 0; j < base; j++) {
count++;
@@ -79,14 +79,14 @@ public class time_complexity {
return count;
}
/* Exponential order (recursive implementation) */
/* Exponential complexity (recursive implementation) */
static int expRecur(int n) {
if (n == 1)
return 1;
return expRecur(n - 1) + expRecur(n - 1) + 1;
}
/* Logarithmic order (loop implementation) */
/* Logarithmic complexity (iterative implementation) */
static int logarithmic(int n) {
int count = 0;
while (n > 1) {
@@ -96,14 +96,14 @@ public class time_complexity {
return count;
}
/* Logarithmic order (recursive implementation) */
/* Logarithmic complexity (recursive implementation) */
static int logRecur(int n) {
if (n <= 1)
return 0;
return logRecur(n / 2) + 1;
}
/* Linearithmic order */
/* Linearithmic complexity */
static int linearLogRecur(int n) {
if (n <= 1)
return 1;
@@ -114,54 +114,54 @@ public class time_complexity {
return count;
}
/* Factorial order (recursive implementation) */
/* Factorial complexity (recursive implementation) */
static int factorialRecur(int n) {
if (n == 0)
return 1;
int count = 0;
// Split from 1 into n
// Split one problem into n subproblems
for (int i = 0; i < n; i++) {
count += factorialRecur(n - 1);
}
return count;
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
// You can modify n to run and observe the trend of the number of operations for various complexities
// Try different values of n to see how the operation count grows for each complexity
int n = 8;
System.out.println("Input data size n = " + n);
System.out.println("Input size n = " + n);
int count = constant(n);
System.out.println("Constant order operation count = " + count);
System.out.println("Operation count for constant complexity = " + count);
count = linear(n);
System.out.println("Linear order operation count = " + count);
System.out.println("Operation count for linear complexity = " + count);
count = arrayTraversal(new int[n]);
System.out.println("Linear order (array traversal) operation count = " + count);
System.out.println("Operation count for linear complexity (array traversal) = " + count);
count = quadratic(n);
System.out.println("Quadratic order operation count = " + count);
System.out.println("Operation count for quadratic complexity = " + count);
int[] nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = n - i; // [n,n-1,...,2,1]
count = bubbleSort(nums);
System.out.println("Quadratic order (bubble sort) operation count = " + count);
System.out.println("Operation count for quadratic complexity (bubble sort) = " + count);
count = exponential(n);
System.out.println("Exponential order (loop implementation) operation count = " + count);
System.out.println("Operation count for exponential complexity (iterative implementation) = " + count);
count = expRecur(n);
System.out.println("Exponential order (recursive implementation) operation count = " + count);
System.out.println("Operation count for exponential complexity (recursive implementation) = " + count);
count = logarithmic(n);
System.out.println("Logarithmic order (loop implementation) operation count = " + count);
System.out.println("Operation count for logarithmic complexity (iterative implementation) = " + count);
count = logRecur(n);
System.out.println("Logarithmic order (recursive implementation) operation count = " + count);
System.out.println("Operation count for logarithmic complexity (recursive implementation) = " + count);
count = linearLogRecur(n);
System.out.println("Linearithmic order (recursive implementation) operation count = " + count);
System.out.println("Operation count for linearithmic complexity (recursive implementation) = " + count);
count = factorialRecur(n);
System.out.println("Factorial order (recursive implementation) operation count = " + count);
System.out.println("Operation count for factorial complexity (recursive implementation) = " + count);
}
}

View File

@@ -9,14 +9,14 @@ package chapter_computational_complexity;
import java.util.*;
public class worst_best_time_complexity {
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
/* Generate an array containing { 1, 2, ..., n } in shuffled order */
static int[] randomNumbers(int n) {
Integer[] nums = new Integer[n];
// Generate array nums = { 1, 2, 3, ..., n }
// Generate the array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Randomly shuffle array elements
// Randomly shuffle the array elements
Collections.shuffle(Arrays.asList(nums));
// Integer[] -> int[]
int[] res = new int[n];
@@ -26,25 +26,25 @@ public class worst_best_time_complexity {
return res;
}
/* Find the index of number 1 in array nums */
/* Find the index of the number 1 in array nums */
static int findOne(int[] nums) {
for (int 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;
}
return -1;
}
/* Driver Code */
/* Driver code */
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int n = 100;
int[] nums = randomNumbers(n);
int index = findOne(nums);
System.out.println("\nArray [ 1, 2, ..., n ] after shuffling = " + Arrays.toString(nums));
System.out.println("Index of number 1 is " + index);
System.out.println("The index of the number 1 is " + index);
}
}
}

View File

@@ -9,20 +9,20 @@ package chapter_divide_and_conquer;
public class binary_search_recur {
/* Binary search: problem f(i, j) */
static int dfs(int[] nums, int target, int i, int 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
int m = (i + j) / 2;
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;
}
}
@@ -30,7 +30,7 @@ public class binary_search_recur {
/* Binary search */
static int binarySearch(int[] nums, int target) {
int n = nums.length;
// Solve the problem f(0, n-1)
// Solve problem f(0, n-1)
return dfs(nums, target, 0, n - 1);
}
@@ -38,7 +38,7 @@ public class binary_search_recur {
int target = 6;
int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 };
// Binary search (closed interval on both sides)
// Binary search (closed interval)
int index = binarySearch(nums, target);
System.out.println("Index of target element 6 = " + index);
}

View File

@@ -10,14 +10,14 @@ import utils.*;
import java.util.*;
public class build_tree {
/* Build binary tree: divide and conquer */
/* Build a binary tree: divide and conquer */
static TreeNode dfs(int[] preorder, Map<Integer, Integer> inorderMap, int i, int l, int 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
TreeNode root = new TreeNode(preorder[i]);
// Query m to divide the left and right subtrees
// Look up m to separate the left and right subtrees
int m = inorderMap.get(preorder[i]);
// Subproblem: build the left subtree
root.left = dfs(preorder, inorderMap, i + 1, l, m - 1);
@@ -27,9 +27,9 @@ public class build_tree {
return root;
}
/* Build binary tree */
/* Build a binary tree */
static TreeNode buildTree(int[] preorder, int[] inorder) {
// Initialize hash map, storing the mapping from inorder elements to indices
// Initialize a hash table mapping each element in inorder to its index
Map<Integer, Integer> inorderMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderMap.put(inorder[i], i);

View File

@@ -7,7 +7,7 @@
package chapter_divide_and_conquer;
public class fast_power {
/* Exponentiation by squaring */
/* Fast exponentiation */
static int fastPow(int x, int n) {
if (n == 0) {
return 1;

View File

@@ -9,9 +9,9 @@ package chapter_divide_and_conquer;
import java.util.*;
public class hanota {
/* Move a disk */
/* Move one disk */
static void move(List<Integer> src, List<Integer> tar) {
// Take out a disk from the top of src
// Take a disk from the top of src
Integer pan = src.remove(src.size() - 1);
// Place the disk on top of tar
tar.add(pan);
@@ -19,14 +19,14 @@ public class hanota {
/* Solve the Tower of Hanoi problem f(i) */
static void dfs(int i, List<Integer> src, List<Integer> buf, List<Integer> 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);
@@ -40,18 +40,18 @@ public class hanota {
}
public static void main(String[] args) {
// The tail of the list is the top of the rod
// The end of each list represents the top of the peg
List<Integer> A = new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));
List<Integer> B = new ArrayList<>();
List<Integer> C = new ArrayList<>();
System.out.println("In initial state:");
System.out.println("Initial state:");
System.out.println("A = " + A);
System.out.println("B = " + B);
System.out.println("C = " + C);
solveHanota(A, B, C);
System.out.println("After disk movement is complete:");
System.out.println("After moving the disks:");
System.out.println("A = " + A);
System.out.println("B = " + B);
System.out.println("C = " + C);

View File

@@ -11,26 +11,26 @@ import java.util.*;
public class climbing_stairs_backtrack {
/* Backtracking */
public static void backtrack(List<Integer> choices, int state, int n, List<Integer> 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 (Integer choice : 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 */
public static int climbingStairsBacktrack(int n) {
List<Integer> choices = Arrays.asList(1, 2); // Can choose to climb up 1 or 2 stairs
int state = 0; // Start climbing from the 0-th stair
List<Integer> choices = Arrays.asList(1, 2); // Choose to climb 1 or 2 steps
int state = 0; // Start climbing from step 0
List<Integer> res = new ArrayList<>();
res.add(0); // Use res[0] to record the solution count
res.add(0); // Use res[0] to record the number of ways
backtrack(choices, state, n, res);
return res.get(0);
}
@@ -39,6 +39,6 @@ public class climbing_stairs_backtrack {
int n = 9;
int res = climbingStairsBacktrack(n);
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
}
}

View File

@@ -7,19 +7,19 @@
package chapter_dynamic_programming;
public class climbing_stairs_constraint_dp {
/* Climbing stairs with constraint: Dynamic programming */
/* Climbing stairs with constraints: dynamic programming */
static int climbingStairsConstraintDP(int 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
int[][] dp = new int[n + 1][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 (int i = 3; i <= n; i++) {
dp[i][1] = dp[i - 1][2];
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
@@ -31,6 +31,6 @@ public class climbing_stairs_constraint_dp {
int n = 9;
int res = climbingStairsConstraintDP(n);
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
}
}

View File

@@ -9,7 +9,7 @@ package chapter_dynamic_programming;
public class climbing_stairs_dfs {
/* Search */
public static int dfs(int 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]
@@ -17,7 +17,7 @@ public class climbing_stairs_dfs {
return count;
}
/* Climbing stairs: Search */
/* Climbing stairs: search */
public static int climbingStairsDFS(int n) {
return dfs(n);
}
@@ -26,6 +26,6 @@ public class climbing_stairs_dfs {
int n = 9;
int res = climbingStairsDFS(n);
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
}
}

View File

@@ -9,12 +9,12 @@ package chapter_dynamic_programming;
import java.util.Arrays;
public class climbing_stairs_dfs_mem {
/* Memoization search */
/* Memoized search */
public static int dfs(int i, int[] 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]
@@ -24,9 +24,9 @@ public class climbing_stairs_dfs_mem {
return count;
}
/* Climbing stairs: Memoization search */
/* Climbing stairs: memoized search */
public static int climbingStairsDFSMem(int 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
int[] mem = new int[n + 1];
Arrays.fill(mem, -1);
return dfs(n, mem);
@@ -36,6 +36,6 @@ public class climbing_stairs_dfs_mem {
int n = 9;
int res = climbingStairsDFSMem(n);
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
}
}

View File

@@ -7,23 +7,23 @@
package chapter_dynamic_programming;
public class climbing_stairs_dp {
/* Climbing stairs: Dynamic programming */
/* Climbing stairs: dynamic programming */
public static int climbingStairsDP(int 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
int[] dp = new int[n + 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 (int 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 */
public static int climbingStairsDPComp(int n) {
if (n == 1 || n == 2)
return n;
@@ -40,9 +40,9 @@ public class climbing_stairs_dp {
int n = 9;
int res = climbingStairsDP(n);
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
res = climbingStairsDPComp(n);
System.out.println(String.format("Climbing %d stairs has %d solutions", n, res));
System.out.println(String.format("Number of ways to climb %d stairs: %d", n, res));
}
}

View File

@@ -9,24 +9,24 @@ package chapter_dynamic_programming;
import java.util.Arrays;
public class coin_change {
/* Coin change: Dynamic programming */
/* Coin change: dynamic programming */
static int coinChangeDP(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize dp table
// Initialize the dp table
int[][] dp = new int[n + 1][amt + 1];
// State transition: first row and first column
// State transitions: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transition: rest of the rows and columns
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int 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);
}
}
@@ -34,22 +34,22 @@ public class coin_change {
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* Coin change: Space-optimized dynamic programming */
/* Coin change: space-optimized dynamic programming */
static int coinChangeDPComp(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize dp table
// Initialize the dp table
int[] dp = new int[amt + 1];
Arrays.fill(dp, MAX);
dp[0] = 0;
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
for (int 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);
}
}
@@ -63,10 +63,10 @@ public class coin_change {
// Dynamic programming
int res = coinChangeDP(coins, amt);
System.out.println("Minimum number of coins needed to make target amount is " + res);
System.out.println("Minimum number of coins needed to make the target amount: " + res);
// Space-optimized dynamic programming
res = coinChangeDPComp(coins, amt);
System.out.println("Minimum number of coins needed to make target amount is " + res);
System.out.println("Minimum number of coins needed to make the target amount: " + res);
}
}

View File

@@ -7,23 +7,23 @@
package chapter_dynamic_programming;
public class coin_change_ii {
/* Coin change II: Dynamic programming */
/* Coin change II: dynamic programming */
static int coinChangeIIDP(int[] coins, int amt) {
int n = coins.length;
// Initialize dp table
// Initialize the dp table
int[][] dp = new int[n + 1][amt + 1];
// Initialize first column
// Initialize the first column
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
for (int 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]];
}
}
@@ -31,20 +31,20 @@ public class coin_change_ii {
return dp[n][amt];
}
/* Coin change II: Space-optimized dynamic programming */
/* Coin change II: space-optimized dynamic programming */
static int coinChangeIIDPComp(int[] coins, int amt) {
int n = coins.length;
// Initialize dp table
// Initialize the dp table
int[] dp = new int[amt + 1];
dp[0] = 1;
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
for (int 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]];
}
}
@@ -58,10 +58,10 @@ public class coin_change_ii {
// Dynamic programming
int res = coinChangeIIDP(coins, amt);
System.out.println("Number of coin combinations to make target amount is " + res);
System.out.println("Number of coin combinations that make the target amount: " + res);
// Space-optimized dynamic programming
res = coinChangeIIDPComp(coins, amt);
System.out.println("Number of coin combinations to make target amount is " + res);
System.out.println("Number of coin combinations that make the target amount: " + res);
}
}

View File

@@ -9,73 +9,73 @@ package chapter_dynamic_programming;
import java.util.Arrays;
public class edit_distance {
/* Edit distance: Brute-force search */
/* Edit distance: brute-force search */
static int editDistanceDFS(String s, String t, int i, int j) {
// If both s and t are empty, return 0
// If the current prefixes of s and t are both 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 j, the length of the current prefix of t
if (i == 0)
return j;
// If t is empty, return length of s
// If the current prefix of t is empty, return i, the length of the current prefix 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
int insert = editDistanceDFS(s, t, i, j - 1);
int delete = editDistanceDFS(s, t, i - 1, j);
int replace = editDistanceDFS(s, t, i - 1, j - 1);
// Return minimum edit steps
// Return the minimum number of edits
return Math.min(Math.min(insert, delete), replace) + 1;
}
/* Edit distance: Memoization search */
/* Edit distance: memoized search */
static int editDistanceDFSMem(String s, String t, int[][] mem, int i, int j) {
// If both s and t are empty, return 0
// If the current prefixes of s and t are both 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 j, the length of the current prefix of t
if (i == 0)
return j;
// If t is empty, return length of s
// If the current prefix of t is empty, return i, the length of the current prefix 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
int insert = editDistanceDFSMem(s, t, mem, i, j - 1);
int delete = editDistanceDFSMem(s, t, mem, i - 1, j);
int 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(Math.min(insert, delete), replace) + 1;
return mem[i][j];
}
/* Edit distance: Dynamic programming */
/* Edit distance: dynamic programming */
static int editDistanceDP(String s, String t) {
int n = s.length(), m = t.length();
int[][] dp = new int[n + 1][m + 1];
// State transition: first row and first column
// State transitions: first row and first column
for (int i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
// State transition: rest of the rows and columns
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int 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(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
@@ -83,30 +83,30 @@ public class edit_distance {
return dp[n][m];
}
/* Edit distance: Space-optimized dynamic programming */
/* Edit distance: space-optimized dynamic programming */
static int editDistanceDPComp(String s, String t) {
int n = s.length(), m = t.length();
int[] dp = new int[m + 1];
// State transition: first row
// State transitions: first row
for (int j = 1; j <= m; j++) {
dp[j] = j;
}
// State transition: rest of the rows
// State transitions: remaining rows
for (int i = 1; i <= n; i++) {
// State transition: first column
// State transitions: first column
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
dp[0] = i;
// State transition: rest of the columns
// State transitions: remaining columns
for (int j = 1; j <= m; j++) {
int 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(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,21 +119,21 @@ public class edit_distance {
// Brute-force search
int res = editDistanceDFS(s, t, n, m);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
// Memoization search
// Memoized search
int[][] mem = new int[n + 1][m + 1];
for (int[] row : mem)
Arrays.fill(row, -1);
res = editDistanceDFSMem(s, t, mem, n, m);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
// Dynamic programming
res = editDistanceDP(s, t);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
// Space-optimized dynamic programming
res = editDistanceDPComp(s, t);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
System.out.println("Changing " + s + " to " + t + " requires at least " + res + " edits");
}
}

View File

@@ -10,58 +10,58 @@ import java.util.Arrays;
public class knapsack {
/* 0-1 knapsack: Brute-force search */
/* 0-1 knapsack: brute-force search */
static int knapsackDFS(int[] wgt, int[] val, int i, int 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
int no = knapsackDFS(wgt, val, i - 1, c);
int 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 */
static int knapsackDFSMem(int[] wgt, int[] val, int[][] mem, int i, int 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
int no = knapsackDFSMem(wgt, val, mem, i - 1, c);
int 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 */
static int knapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
// Initialize the dp table
int[][] dp = new int[n + 1][cap + 1];
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
for (int 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 @@ public class knapsack {
return dp[n][cap];
}
/* 0-1 knapsack: Space-optimized dynamic programming */
/* 0-1 knapsack: space-optimized dynamic programming */
static int knapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
// Initialize the dp table
int[] dp = new int[cap + 1];
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
// Traverse in reverse order
// Traverse in decreasing order
for (int 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]);
}
}
@@ -95,22 +95,22 @@ public class knapsack {
// Brute-force search
int res = knapsackDFS(wgt, val, n, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
// Memoization search
// Memoized search
int[][] mem = new int[n + 1][cap + 1];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = knapsackDFSMem(wgt, val, mem, n, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
// Dynamic programming
res = knapsackDP(wgt, val, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
// Space-optimized dynamic programming
res = knapsackDPComp(wgt, val, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
}
}

View File

@@ -9,24 +9,24 @@ package chapter_dynamic_programming;
import java.util.Arrays;
public class min_cost_climbing_stairs_dp {
/* Minimum cost climbing stairs: Dynamic programming */
/* Minimum cost to climb stairs: dynamic programming */
public static int minCostClimbingStairsDP(int[] cost) {
int 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
int[] dp = new int[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 (int 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 */
public static int minCostClimbingStairsDPComp(int[] cost) {
int n = cost.length - 1;
if (n == 1 || n == 2)
@@ -42,12 +42,12 @@ public class min_cost_climbing_stairs_dp {
public static void main(String[] args) {
int[] cost = { 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
System.out.println(String.format("Input staircase cost list is %s", Arrays.toString(cost)));
System.out.println(String.format("Input stair costs: %s", Arrays.toString(cost)));
int res = minCostClimbingStairsDP(cost);
System.out.println(String.format("Minimum cost to climb staircase is %d", res));
System.out.println(String.format("Minimum cost to climb the stairs: %d", res));
res = minCostClimbingStairsDPComp(cost);
System.out.println(String.format("Minimum cost to climb staircase is %d", res));
System.out.println(String.format("Minimum cost to climb the stairs: %d", res));
}
}

View File

@@ -9,60 +9,60 @@ package chapter_dynamic_programming;
import java.util.Arrays;
public class min_path_sum {
/* Minimum path sum: Brute-force search */
/* Minimum path sum: brute-force search */
static int minPathSumDFS(int[][] grid, int i, int 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 Integer.MAX_VALUE;
}
// 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)
int up = minPathSumDFS(grid, i - 1, j);
int 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 */
static int minPathSumDFSMem(int[][] grid, int[][] mem, int i, int 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 Integer.MAX_VALUE;
}
// 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
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int 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 */
static int minPathSumDP(int[][] grid) {
int n = grid.length, m = grid[0].length;
// Initialize dp table
// Initialize the dp table
int[][] dp = new int[n][m];
dp[0][0] = grid[0][0];
// State transition: first row
// State transitions: first row
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transition: first column
// State transitions: first column
for (int 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 (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
@@ -71,21 +71,21 @@ public class min_path_sum {
return dp[n - 1][m - 1];
}
/* Minimum path sum: Space-optimized dynamic programming */
/* Minimum path sum: space-optimized dynamic programming */
static int minPathSumDPComp(int[][] grid) {
int n = grid.length, m = grid[0].length;
// Initialize dp table
// Initialize the dp table
int[] dp = new int[m];
// State transition: first row
// State transitions: first row
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transition: rest of the rows
// State transitions: remaining rows
for (int 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 (int j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
@@ -104,22 +104,22 @@ public class min_path_sum {
// Brute-force search
int res = minPathSumDFS(grid, n - 1, m - 1);
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
// Memoization search
// Memoized search
int[][] mem = new int[n][m];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
// Dynamic programming
res = minPathSumDP(grid);
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
// Space-optimized dynamic programming
res = minPathSumDPComp(grid);
System.out.println("Minimum path sum from top-left to bottom-right is " + res);
System.out.println("Minimum path sum from the top-left to the bottom-right corner: " + res);
}
}

View File

@@ -7,19 +7,19 @@
package chapter_dynamic_programming;
public class unbounded_knapsack {
/* Unbounded knapsack: Dynamic programming */
/* Unbounded knapsack: dynamic programming */
static int unboundedKnapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
// Initialize the dp table
int[][] dp = new int[n + 1][cap + 1];
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
for (int 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]);
}
}
@@ -27,19 +27,19 @@ public class unbounded_knapsack {
return dp[n][cap];
}
/* Unbounded knapsack: Space-optimized dynamic programming */
/* Unbounded knapsack: space-optimized dynamic programming */
static int unboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
// Initialize the dp table
int[] dp = new int[cap + 1];
// State transition
// State transitions
for (int i = 1; i <= n; i++) {
for (int 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]);
}
}
@@ -54,10 +54,10 @@ public class unbounded_knapsack {
// Dynamic programming
int res = unboundedKnapsackDP(wgt, val, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(wgt, val, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
}
}

View File

@@ -9,9 +9,9 @@ package chapter_graph;
import java.util.*;
import utils.*;
/* 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
Map<Vertex, List<Vertex>> adjList;
/* Constructor */
@@ -30,7 +30,7 @@ class GraphAdjList {
return adjList.size();
}
/* Add edge */
/* Add an edge */
public void addEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw new IllegalArgumentException();
@@ -39,7 +39,7 @@ class GraphAdjList {
adjList.get(vet2).add(vet1);
}
/* Remove edge */
/* Remove an edge */
public void removeEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw new IllegalArgumentException();
@@ -48,27 +48,27 @@ class GraphAdjList {
adjList.get(vet2).remove(vet1);
}
/* Add vertex */
/* Add a vertex */
public void addVertex(Vertex vet) {
if (adjList.containsKey(vet))
return;
// Add a new linked list in the adjacency list
// Add a new list to the adjacency list
adjList.put(vet, new ArrayList<>());
}
/* Remove vertex */
/* Remove a vertex */
public void removeVertex(Vertex vet) {
if (!adjList.containsKey(vet))
throw new IllegalArgumentException();
// Remove the linked list corresponding to vertex vet in the adjacency list
// Remove the list corresponding to vertex vet from the adjacency list
adjList.remove(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 (List<Vertex> list : adjList.values()) {
list.remove(vet);
}
}
/* Print adjacency list */
/* Print the adjacency list */
public void print() {
System.out.println("Adjacency list =");
for (Map.Entry<Vertex, List<Vertex>> pair : adjList.entrySet()) {
@@ -82,36 +82,36 @@ class GraphAdjList {
public class graph_adjacency_list {
public static void main(String[] args) {
/* Add edge */
/* Initialize the undirected graph */
Vertex[] v = Vertex.valsToVets(new int[] { 1, 3, 2, 5, 4 });
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] },
{ v[2], v[3] }, { v[2], v[4] }, { v[3], v[4] } };
GraphAdjList graph = new GraphAdjList(edges);
System.out.println("\nAfter initialization, graph is");
System.out.println("\nGraph after initialization:");
graph.print();
/* Add edge */
// Vertices 1, 3 are v[0], v[1]
/* Add an edge */
// Vertices 1 and 2 are v[0] and v[2]
graph.addEdge(v[0], v[2]);
System.out.println("\nAfter adding edge 1-2, graph is");
System.out.println("\nGraph after adding edge 1-2:");
graph.print();
/* Remove edge */
// Vertex 3 is v[1]
/* Remove an edge */
// Vertices 1 and 3 are v[0] and v[1]
graph.removeEdge(v[0], v[1]);
System.out.println("\nAfter removing edge 1-3, graph is");
System.out.println("\nGraph after removing edge 1-3:");
graph.print();
/* Add vertex */
/* Add a vertex */
Vertex v5 = new Vertex(6);
graph.addVertex(v5);
System.out.println("\nAfter adding vertex 6, graph is");
System.out.println("\nGraph after adding vertex 6:");
graph.print();
/* Remove vertex */
/* Remove a vertex */
// Vertex 3 is v[1]
graph.removeVertex(v[1]);
System.out.println("\nAfter removing vertex 3, graph is");
System.out.println("\nGraph after removing vertex 3:");
graph.print();
}
}

View File

@@ -9,21 +9,21 @@ package chapter_graph;
import utils.*;
import java.util.*;
/* Undirected graph class based on adjacency matrix */
/* Undirected graph class implemented with an adjacency matrix */
class GraphAdjMat {
List<Integer> vertices; // Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
List<List<Integer>> adjMat; // Adjacency matrix, where the row and column indices correspond to the "vertex index"
List<Integer> vertices; // Vertex list: elements are vertex values, and indices are vertex indices
List<List<Integer>> adjMat; // Adjacency matrix: row and column indices correspond to vertex indices
/* Constructor */
public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = new ArrayList<>();
this.adjMat = new ArrayList<>();
// Add vertex
// Add a vertex
for (int val : vertices) {
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 (int[] e : edges) {
addEdge(e[0], e[1]);
}
@@ -34,10 +34,10 @@ class GraphAdjMat {
return vertices.size();
}
/* Add vertex */
/* Add a vertex */
public void addVertex(int val) {
int n = size();
// Add the value of the new vertex to the vertex list
// Append the new vertex value to the vertex list
vertices.add(val);
// Add a row to the adjacency matrix
List<Integer> newRow = new ArrayList<>(n);
@@ -51,42 +51,42 @@ class GraphAdjMat {
}
}
/* Remove vertex */
/* Remove a vertex */
public void removeVertex(int index) {
if (index >= size())
throw new IndexOutOfBoundsException();
// Remove the vertex at index from the vertex list
// Remove the vertex at index `index` from the vertex list
vertices.remove(index);
// Remove the row at index from the adjacency matrix
// Remove row `index` from the adjacency matrix
adjMat.remove(index);
// Remove the column at index from the adjacency matrix
// Remove column `index` from the adjacency matrix
for (List<Integer> row : adjMat) {
row.remove(index);
}
}
/* Add edge */
// Parameters i, j correspond to the vertices element indices
/* Add an edge */
// Parameters i and j are element indices in vertices
public void addEdge(int i, int j) {
// Handle index out of bounds and equality
// Handle out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw new IndexOutOfBoundsException();
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
// For an undirected graph, the adjacency matrix is symmetric about its main diagonal: entries (i, j) and (j, i) are equal
adjMat.get(i).set(j, 1);
adjMat.get(j).set(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
public void removeEdge(int i, int j) {
// Handle index out of bounds and equality
// Handle out-of-bounds or equal indices
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw new IndexOutOfBoundsException();
adjMat.get(i).set(j, 0);
adjMat.get(j).set(i, 0);
}
/* Print adjacency matrix */
/* Print the adjacency matrix */
public void print() {
System.out.print("Vertex list = ");
System.out.println(vertices);
@@ -97,35 +97,35 @@ class GraphAdjMat {
public class graph_adjacency_matrix {
public static void main(String[] args) {
/* Add edge */
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
/* Initialize the undirected graph */
// Note that the entries in edges are vertex indices, corresponding to element indices in vertices
int[] vertices = { 1, 3, 2, 5, 4 };
int[][] edges = { { 0, 1 }, { 0, 3 }, { 1, 2 }, { 2, 3 }, { 2, 4 }, { 3, 4 } };
GraphAdjMat graph = new GraphAdjMat(vertices, edges);
System.out.println("\nAfter initialization, graph is");
System.out.println("\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);
System.out.println("\nAfter adding edge 1-2, graph is");
System.out.println("\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);
System.out.println("\nAfter removing edge 1-3, graph is");
System.out.println("\nGraph after removing edge 1-3:");
graph.print();
/* Add vertex */
/* Add a vertex */
graph.addVertex(6);
System.out.println("\nAfter adding vertex 6, graph is");
System.out.println("\nGraph after adding vertex 6:");
graph.print();
/* Remove vertex */
/* Remove a vertex */
// Vertex 3 has index 1
graph.removeVertex(1);
System.out.println("\nAfter removing vertex 3, graph is");
System.out.println("\nGraph after removing vertex 3:");
graph.print();
}
}

View File

@@ -11,45 +11,45 @@ import utils.*;
public class graph_bfs {
/* 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
static List<Vertex> graphBFS(GraphAdjList graph, Vertex startVet) {
// Vertex traversal sequence
List<Vertex> res = new ArrayList<>();
// Hash set for recording vertices that have been visited
// Hash set recording visited vertices
Set<Vertex> visited = new HashSet<>();
visited.add(startVet);
// Queue used to implement BFS
// Use a queue to implement BFS
Queue<Vertex> que = new LinkedList<>();
que.offer(startVet);
// Starting from vertex vet, loop until all vertices are visited
// Starting from startVet, loop until all reachable vertices have been visited
while (!que.isEmpty()) {
Vertex vet = que.poll(); // Dequeue the front vertex
res.add(vet); // Record visited vertex
// Traverse all adjacent vertices of this vertex
res.add(vet); // Record the visited vertex
// Traverse all neighbors of this vertex
for (Vertex adjVet : graph.adjList.get(vet)) {
if (visited.contains(adjVet))
continue; // Skip vertices that have been visited
que.offer(adjVet); // Only enqueue unvisited vertices
continue; // Skip vertices that have already been visited
que.offer(adjVet); // Enqueue only unvisited vertices
visited.add(adjVet); // Mark this vertex as visited
}
}
// Return vertex traversal sequence
// Return the vertex traversal sequence
return res;
}
public static void main(String[] args) {
/* Add edge */
/* Initialize the undirected graph */
Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[1], v[4] },
{ v[2], v[5] }, { v[3], v[4] }, { v[3], v[6] }, { v[4], v[5] },
{ v[4], v[7] }, { v[5], v[8] }, { v[6], v[7] }, { v[7], v[8] } };
GraphAdjList graph = new GraphAdjList(edges);
System.out.println("\nAfter initialization, graph is");
System.out.println("\nGraph after initialization:");
graph.print();
/* Breadth-first traversal */
List<Vertex> res = graphBFS(graph, v[0]);
System.out.println("\nBreadth-first traversal (BFS) vertex sequence is");
System.out.println("\nVertex sequence from breadth-first traversal (BFS):");
System.out.println(Vertex.vetsToVals(res));
}
}

View File

@@ -12,40 +12,40 @@ import utils.*;
public class graph_dfs {
/* Depth-first traversal helper function */
static void dfs(GraphAdjList graph, Set<Vertex> visited, List<Vertex> res, Vertex vet) {
res.add(vet); // Record visited vertex
res.add(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 (Vertex adjVet : graph.adjList.get(vet)) {
if (visited.contains(adjVet))
continue; // Skip vertices that have been visited
// Recursively visit adjacent vertices
continue; // Skip vertices that have already been visited
// 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
static List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) {
// Vertex traversal sequence
List<Vertex> res = new ArrayList<>();
// Hash set for recording vertices that have been visited
// Hash set recording visited vertices
Set<Vertex> visited = new HashSet<>();
dfs(graph, visited, res, startVet);
return res;
}
public static void main(String[] args) {
/* Add edge */
/* Initialize the undirected graph */
Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6 });
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] },
{ v[2], v[5] }, { v[4], v[5] }, { v[5], v[6] } };
GraphAdjList graph = new GraphAdjList(edges);
System.out.println("\nAfter initialization, graph is");
System.out.println("\nGraph after initialization:");
graph.print();
/* Depth-first traversal */
List<Vertex> res = graphDFS(graph, v[0]);
System.out.println("\nDepth-first traversal (DFS) vertex sequence is");
System.out.println("\nVertex sequence from depth-first traversal (DFS):");
System.out.println(Vertex.vetsToVals(res));
}
}

View File

@@ -9,14 +9,14 @@ package chapter_greedy;
import java.util.Arrays;
public class coin_change_greedy {
/* Coin change: Greedy algorithm */
/* Coin change: greedy algorithm */
static int coinChangeGreedy(int[] coins, int amt) {
// Assume coins list is sorted
// Assume the coins list is sorted
int i = coins.length - 1;
int 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--;
}
@@ -24,32 +24,32 @@ public class coin_change_greedy {
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;
}
public static void main(String[] args) {
// Greedy algorithm: Can guarantee finding the global optimal solution
// Greedy algorithm: guaranteed to find a globally optimal solution
int[] coins = { 1, 5, 10, 20, 50, 100 };
int amt = 186;
int res = coinChangeGreedy(coins, amt);
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
System.out.println("Minimum number of coins needed to make " + amt + " is " + res);
System.out.println("For amount " + amt + " the greedy coin count is " + res);
// Greedy algorithm: Cannot guarantee finding the global optimal solution
// Greedy algorithm: not guaranteed to find a globally optimal solution
coins = new int[] { 1, 20, 50 };
amt = 60;
res = coinChangeGreedy(coins, amt);
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
System.out.println("Minimum number of coins needed to make " + amt + " is " + res);
System.out.println("Actually the minimum number needed is 3, i.e., 20 + 20 + 20");
System.out.println("For amount " + amt + " the greedy coin count is " + res);
System.out.println("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 = new int[] { 1, 49, 50 };
amt = 98;
res = coinChangeGreedy(coins, amt);
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
System.out.println("Minimum number of coins needed to make " + amt + " is " + res);
System.out.println("Actually the minimum number needed is 2, i.e., 49 + 49");
System.out.println("For amount " + amt + " the greedy coin count is " + res);
System.out.println("The actual minimum is 2 coins: 49 + 49");
}
}

View File

@@ -21,26 +21,26 @@ class Item {
}
public class fractional_knapsack {
/* Fractional knapsack: Greedy algorithm */
/* Fractional knapsack: greedy algorithm */
static double fractionalKnapsack(int[] wgt, int[] val, int cap) {
// Create item list with two attributes: weight, value
// Create a list of items, each with two attributes: weight and value
Item[] items = new Item[wgt.length];
for (int i = 0; i < wgt.length; i++) {
items[i] = new Item(wgt[i], 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
Arrays.sort(items, Comparator.comparingDouble(item -> -((double) item.v / item.w)));
// Loop for greedy selection
// Repeatedly make greedy choices
double res = 0;
for (Item item : 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 += (double) item.v / item.w * cap;
// No remaining capacity, so break out of the loop
// No capacity remains, so exit the loop
break;
}
}
@@ -54,6 +54,6 @@ public class fractional_knapsack {
// Greedy algorithm
double res = fractionalKnapsack(wgt, val, cap);
System.out.println("Maximum item value not exceeding knapsack capacity is " + res);
System.out.println("Maximum total item value within the knapsack capacity: " + res);
}
}

View File

@@ -7,18 +7,18 @@
package chapter_greedy;
public class max_capacity {
/* Max capacity: Greedy algorithm */
/* Maximum container capacity: greedy algorithm */
static int maxCapacity(int[] ht) {
// Initialize i, j to be at both ends of the array
// Initialize i and j at opposite ends of the array
int i = 0, j = ht.length - 1;
// Initial max capacity is 0
// The initial maximum capacity is 0
int 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
int 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++;
} else {
@@ -33,6 +33,6 @@ public class max_capacity {
// Greedy algorithm
int res = maxCapacity(ht);
System.out.println("Maximum capacity is " + res);
System.out.println("Maximum container capacity: " + res);
}
}

View File

@@ -9,24 +9,24 @@ package chapter_greedy;
import java.lang.Math;
public class max_product_cutting {
/* Max product cutting: Greedy algorithm */
/* Maximum product after splitting: greedy algorithm */
public static int maxProductCutting(int 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
int a = n / 3;
int 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 (int) 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 (int) Math.pow(3, a) * 2;
}
// When the remainder is 0, do nothing
// When the remainder is 0, no adjustment is needed
return (int) Math.pow(3, a);
}
@@ -35,6 +35,6 @@ public class max_product_cutting {
// Greedy algorithm
int res = maxProductCutting(n);
System.out.println("Maximum cutting product is " + res);
System.out.println("Maximum product after splitting: " + res);
}
}

View File

@@ -19,12 +19,12 @@ class Pair {
}
}
/* Hash table based on array implementation */
/* Hash table implemented with an array */
class ArrayHashMap {
private List<Pair> buckets;
public ArrayHashMap() {
// Initialize array with 100 buckets
// Initialize an array containing 100 buckets
buckets = new ArrayList<>();
for (int i = 0; i < 100; i++) {
buckets.add(null);
@@ -37,7 +37,7 @@ class ArrayHashMap {
return index;
}
/* Query operation */
/* Lookup operation */
public String get(int key) {
int index = hashFunc(key);
Pair pair = buckets.get(index);
@@ -46,7 +46,7 @@ class ArrayHashMap {
return pair.val;
}
/* Add operation */
/* Insert operation */
public void put(int key, String val) {
Pair pair = new Pair(key, val);
int index = hashFunc(key);
@@ -56,7 +56,7 @@ class ArrayHashMap {
/* Remove operation */
public void remove(int key) {
int index = hashFunc(key);
// Set to null to represent deletion
// Set the bucket to null to mark it as removed
buckets.set(index, null);
}
@@ -90,7 +90,7 @@ class ArrayHashMap {
return valueSet;
}
/* Print hash table */
/* Print the hash table */
public void print() {
for (Pair kv : pairSet()) {
System.out.println(kv.key + " -> " + kv.val);
@@ -100,40 +100,40 @@ class ArrayHashMap {
public class array_hash_map {
public static void main(String[] args) {
/* Initialize hash table */
/* Initialize the hash table */
ArrayHashMap map = new ArrayHashMap();
/* 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");
System.out.println("\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, "小鸭");
System.out.println("\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
String name = map.get(15937);
System.out.println("\nInput student ID 15937, query name " + name);
System.out.println("\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.remove(10583);
System.out.println("\nAfter removing 10583, hash table is\nKey -> Value");
System.out.println("\nHash table after removing 10583:\nKey -> Value");
map.print();
/* Traverse hash table */
System.out.println("\nTraverse key-value pairs Key->Value");
/* Traverse the hash table */
System.out.println("\nTraverse key-value pairs: Key->Value");
for (Pair kv : map.pairSet()) {
System.out.println(kv.key + " -> " + kv.val);
}
System.out.println("\nTraverse keys only Key");
System.out.println("\nTraverse keys only: Key");
for (int key : map.keySet()) {
System.out.println(key);
}
System.out.println("\nTraverse values only Value");
System.out.println("\nTraverse values only: Value");
for (String val : map.valueSet()) {
System.out.println(val);
}

View File

@@ -13,26 +13,26 @@ public class built_in_hash {
public static void main(String[] args) {
int num = 3;
int hashNum = Integer.hashCode(num);
System.out.println("Hash value of integer " + num + " is " + hashNum);
System.out.println("Integer " + num + " has hash value " + hashNum);
boolean bol = true;
int hashBol = Boolean.hashCode(bol);
System.out.println("Hash value of boolean " + bol + " is " + hashBol);
System.out.println("Boolean " + bol + " has hash value " + hashBol);
double dec = 3.14159;
int hashDec = Double.hashCode(dec);
System.out.println("Hash value of decimal " + dec + " is " + hashDec);
System.out.println("Decimal " + dec + " has hash value " + hashDec);
String str = "Hello Algo";
String str = "Hello 算法";
int hashStr = str.hashCode();
System.out.println("Hash value of string " + str + " is " + hashStr);
System.out.println("String " + str + " has hash value " + hashStr);
Object[] arr = { 12836, "Xiao Ha" };
Object[] arr = { 12836, "小哈" };
int hashTup = Arrays.hashCode(arr);
System.out.println("Hash value of array " + Arrays.toString(arr) + " is " + hashTup);
System.out.println("Array " + Arrays.toString(arr) + " has hash value " + hashTup);
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode();
System.out.println("Hash value of node object " + obj + " is " + hashObj);
System.out.println("Node object " + obj + " has hash value " + hashObj);
}
}

View File

@@ -11,40 +11,40 @@ import utils.*;
public class hash_map {
public static void main(String[] args) {
/* Initialize hash table */
/* Initialize the hash table */
Map<Integer, String> map = new HashMap<>();
/* 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");
System.out.println("\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, "小鸭");
System.out.println("\nHash table after insertion:\nKey -> Value");
PrintUtil.printHashMap(map);
/* Query operation */
// Input key into hash table to get value
/* Lookup operation */
// Look up key in the hash table to obtain value
String name = map.get(15937);
System.out.println("\nInput student ID 15937, query name " + name);
System.out.println("\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.remove(10583);
System.out.println("\nAfter removing 10583, hash table is\nKey -> Value");
System.out.println("\nHash table after removing 10583:\nKey -> Value");
PrintUtil.printHashMap(map);
/* Traverse hash table */
System.out.println("\nTraverse key-value pairs Key->Value");
/* Traverse the hash table */
System.out.println("\nTraverse key-value pairs: Key->Value");
for (Map.Entry<Integer, String> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
System.out.println("\nTraverse keys only Key");
System.out.println("\nTraverse keys only: Key");
for (int key : map.keySet()) {
System.out.println(key);
}
System.out.println("\nTraverse values only Value");
System.out.println("\nTraverse values only: Value");
for (String val : map.values()) {
System.out.println(val);
}

View File

@@ -13,8 +13,8 @@ import java.util.List;
class HashMapChaining {
int size; // Number of key-value pairs
int capacity; // Hash table capacity
double loadThres; // Load factor threshold for triggering expansion
int extendRatio; // Expansion multiplier
double loadThres; // Load factor threshold that triggers capacity growth
int extendRatio; // Capacity growth factor
List<List<Pair>> buckets; // Bucket array
/* Constructor */
@@ -39,36 +39,36 @@ class HashMapChaining {
return (double) size / capacity;
}
/* Query operation */
/* Lookup operation */
String get(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// Traverse bucket, if key is found, return corresponding val
// Traverse the bucket; if key is found, return its corresponding val
for (Pair pair : bucket) {
if (pair.key == key) {
return pair.val;
}
}
// If key is not found, return null
// Return null if key is not found
return null;
}
/* Add operation */
/* Insert operation */
void put(int key, String val) {
// When load factor exceeds threshold, perform expansion
// Grow the capacity when the load factor exceeds the threshold
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
List<Pair> bucket = buckets.get(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 (Pair pair : 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
Pair pair = new Pair(key, val);
bucket.add(pair);
size++;
@@ -78,7 +78,7 @@ class HashMapChaining {
void remove(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// Traverse bucket and remove key-value pair from it
// Traverse the bucket and remove the key-value pair
for (Pair pair : bucket) {
if (pair.key == key) {
bucket.remove(pair);
@@ -88,18 +88,18 @@ class HashMapChaining {
}
}
/* Expand hash table */
/* Grow the hash table capacity */
void extend() {
// Temporarily store the original hash table
// Keep a reference to the original hash table
List<List<Pair>> bucketsTmp = buckets;
// Initialize expanded new hash table
// Initialize a new hash table with the expanded capacity
capacity *= extendRatio;
buckets = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.add(new ArrayList<>());
}
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 (List<Pair> bucket : bucketsTmp) {
for (Pair pair : bucket) {
put(pair.key, pair.val);
@@ -107,7 +107,7 @@ class HashMapChaining {
}
}
/* Print hash table */
/* Print the hash table */
void print() {
for (List<Pair> bucket : buckets) {
List<String> res = new ArrayList<>();
@@ -121,28 +121,28 @@ class HashMapChaining {
public class hash_map_chaining {
public static void main(String[] args) {
/* Initialize hash table */
/* Initialize the hash table */
HashMapChaining 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");
System.out.println("\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, "小鸭");
System.out.println("\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
String name = map.get(13276);
System.out.println("\nInput student ID 13276, query name " + name);
System.out.println("\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);
System.out.println("\nAfter removing 12836, hash table is\nKey -> Value");
System.out.println("\nHash table after removing 12836:\nKey -> Value");
map.print();
}
}

View File

@@ -10,10 +10,10 @@ package chapter_hashing;
class HashMapOpenAddressing {
private int size; // Number of key-value pairs
private int capacity = 4; // Hash table capacity
private final double loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
private final int extendRatio = 2; // Expansion multiplier
private final double loadThres = 2.0 / 3.0; // Load factor threshold that triggers capacity growth
private final int extendRatio = 2; // Capacity growth factor
private Pair[] buckets; // Bucket array
private final Pair TOMBSTONE = new Pair(-1, "-1"); // Removal marker
private final Pair TOMBSTONE = new Pair(-1, "-1"); // Tombstone marker
/* Constructor */
public HashMapOpenAddressing() {
@@ -31,83 +31,83 @@ class HashMapOpenAddressing {
return (double) size / capacity;
}
/* Search for bucket index corresponding to key */
/* Find the bucket index for key */
private int findBucket(int key) {
int index = hashFunc(key);
int firstTombstone = -1;
// Linear probing, break when encountering an empty bucket
// Probe linearly until an empty bucket is reached
while (buckets[index] != null) {
// If key is encountered, return the corresponding bucket index
// If key is found, return its bucket index
if (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) {
buckets[firstTombstone] = buckets[index];
buckets[index] = 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 && buckets[index] == 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) % 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 */
public String get(int key) {
// Search for bucket index corresponding to key
// Find the bucket index for key
int index = findBucket(key);
// If key-value pair is found, return corresponding val
// If the key-value pair is found, return its val
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
return buckets[index].val;
}
// If key-value pair does not exist, return null
// Return null if the key-value pair is absent
return null;
}
/* Add operation */
/* Insert operation */
public void put(int key, String val) {
// When load factor exceeds threshold, perform expansion
// Grow the capacity when the load factor exceeds the threshold
if (loadFactor() > loadThres) {
extend();
}
// Search for bucket index corresponding to key
// Find the bucket index for key
int index = findBucket(key);
// If key-value pair is found, overwrite val and return
// If the key-value pair is found, overwrite val and return
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
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
buckets[index] = new Pair(key, val);
size++;
}
/* Remove operation */
public void remove(int key) {
// Search for bucket index corresponding to key
// Find the bucket index for key
int index = 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 (buckets[index] != null && buckets[index] != TOMBSTONE) {
buckets[index] = TOMBSTONE;
size--;
}
}
/* Expand hash table */
/* Grow the hash table capacity */
private void extend() {
// Temporarily store the original hash table
// Keep a reference to the original hash table
Pair[] bucketsTmp = buckets;
// Initialize expanded new hash table
// Initialize a new hash table with the expanded capacity
capacity *= extendRatio;
buckets = new Pair[capacity];
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 (Pair pair : bucketsTmp) {
if (pair != null && pair != TOMBSTONE) {
put(pair.key, pair.val);
@@ -115,7 +115,7 @@ class HashMapOpenAddressing {
}
}
/* Print hash table */
/* Print the hash table */
public void print() {
for (Pair pair : buckets) {
if (pair == null) {
@@ -131,28 +131,28 @@ class HashMapOpenAddressing {
public class hash_map_open_addressing {
public static void main(String[] args) {
// Initialize hash table
// Initialize the hash table
HashMapOpenAddressing 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");
System.out.println("\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, "小鸭");
System.out.println("\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
String name = hashmap.get(13276);
System.out.println("\nInput student ID 13276, query name " + name);
System.out.println("\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);
System.out.println("\nAfter removing 16750, hash table is\nKey -> Value");
System.out.println("\nHash table after removing 16750:\nKey -> Value");
hashmap.print();
}
}

View File

@@ -37,7 +37,7 @@ public class simple_hash {
return hash & MODULUS;
}
/* Rotational hash */
/* Rotating hash */
static int rotHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
@@ -48,18 +48,18 @@ public class simple_hash {
}
public static void main(String[] args) {
String key = "Hello Algo";
String key = "Hello 算法";
int hash = addHash(key);
System.out.println("Additive hash value is " + hash);
System.out.println("Additive hash value: " + hash);
hash = mulHash(key);
System.out.println("Multiplicative hash value is " + hash);
System.out.println("Multiplicative hash value: " + hash);
hash = xorHash(key);
System.out.println("XOR hash value is " + hash);
System.out.println("XOR hash value: " + hash);
hash = rotHash(key);
System.out.println("Rotational hash value is " + hash);
System.out.println("Rotating hash value: " + hash);
}
}

View File

@@ -11,56 +11,56 @@ import java.util.*;
public class heap {
public static void testPush(Queue<Integer> heap, int val) {
heap.offer(val); // Element enters heap
System.out.format("\nAfter element %d enters heap\n", val);
heap.offer(val); // Push an element onto the heap
System.out.format("\nAfter pushing %d onto the heap:\n", val);
PrintUtil.printHeap(heap);
}
public static void testPop(Queue<Integer> heap) {
int val = heap.poll(); // Time complexity is O(n), not O(nlogn)
System.out.format("\nAfter heap top element %d exits heap\n", val);
int val = heap.poll(); // Pop the top element from the heap
System.out.format("\nAfter popping the top element %d:\n", val);
PrintUtil.printHeap(heap);
}
public static void main(String[] args) {
/* Initialize heap */
// Python's heapq module implements min heap by default
/* Initialize heaps */
// Initialize a min heap
Queue<Integer> minHeap = new PriorityQueue<>();
// Initialize max heap (modify Comparator using lambda expression)
// Initialize a max heap by supplying a lambda expression as the Comparator
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
System.out.println("\nThe following test cases are for max heap");
System.out.println("\nThe following example uses a max heap");
/* Element enters heap */
/* Push an element onto the heap */
testPush(maxHeap, 1);
testPush(maxHeap, 3);
testPush(maxHeap, 2);
testPush(maxHeap, 5);
testPush(maxHeap, 4);
/* Check if heap is empty */
/* Get the top element of the heap */
int peek = maxHeap.peek();
System.out.format("\nHeap top element is %d\n", peek);
System.out.format("\nTop element: %d\n", peek);
/* Time complexity is O(n), not O(nlogn) */
/* Pop the top element from the heap */
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
/* Get heap size */
/* Get the heap size */
int size = maxHeap.size();
System.out.format("\nHeap element count is %d\n", size);
System.out.format("\nNumber of elements in the heap: %d\n", size);
/* Check if heap is empty */
/* Check whether the heap is empty */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\nHeap is empty %b\n", isEmpty);
System.out.format("\nIs the heap empty? %b\n", isEmpty);
/* Input list and build heap */
// Time complexity is O(n), not O(nlogn)
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
System.out.println("\nAfter inputting list and building min heap");
System.out.println("\nAfter building a min heap from the input list:");
PrintUtil.printHeap(minHeap);
}
}

View File

@@ -11,32 +11,32 @@ import java.util.*;
/* Max heap */
class MaxHeap {
// Use list instead of array, no need to consider capacity expansion
// Use a resizable list instead of an array to avoid managing capacity growth
private List<Integer> maxHeap;
/* Constructor, build heap based on input list */
/* Constructor: build a heap from the input list */
public MaxHeap(List<Integer> nums) {
// Add list elements to heap as is
// Place the list elements in the heap without changing their order
maxHeap = new ArrayList<>(nums);
// Heapify all nodes except leaf nodes
// Sift down from every non-leaf node
for (int i = parent(size() - 1); i >= 0; i--) {
siftDown(i);
}
}
/* Get index of left child node */
/* Get the left child index */
private int left(int i) {
return 2 * i + 1;
}
/* Get index of right child node */
/* Get the right child index */
private int right(int i) {
return 2 * i + 2;
}
/* Get index of parent node */
/* Get the parent index */
private int parent(int i) {
return (i - 1) / 2; // Floor division
return (i - 1) / 2; // Integer division (truncates toward zero in Java)
}
/* Swap elements */
@@ -46,79 +46,79 @@ class MaxHeap {
maxHeap.set(j, tmp);
}
/* Get heap size */
/* Get the heap size */
public int size() {
return maxHeap.size();
}
/* Check if heap is empty */
/* Check whether the heap is empty */
public boolean isEmpty() {
return size() == 0;
}
/* Access top element */
/* Access the top element of the heap */
public int peek() {
return maxHeap.get(0);
}
/* Element enters heap */
/* Push an element onto the heap */
public void push(int val) {
// Add node
// Add a node
maxHeap.add(val);
// Heapify from bottom to top
// Sift up
siftUp(size() - 1);
}
/* Starting from node i, heapify from bottom to top */
/* Sift up starting from node i */
private void siftUp(int i) {
while (true) {
// Get parent node of node i
// Get the parent of node i
int p = 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 || maxHeap.get(i) <= maxHeap.get(p))
break;
// Swap two nodes
// Swap the two nodes
swap(i, p);
// Loop upward heapify
// Continue sifting up
i = p;
}
}
/* Element exits heap */
/* Pop an element from the heap */
public int pop() {
// Handle empty case
// Handle an empty heap
if (isEmpty())
throw new IndexOutOfBoundsException();
// Delete node
// Swap the root with the rightmost leaf on the last level (swap the first and last elements)
swap(0, size() - 1);
// Remove node
// Remove a node
int val = maxHeap.remove(size() - 1);
// Return top element
// Sift down
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 */
private void siftDown(int 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
int l = left(i), r = right(i), ma = i;
if (l < size() && maxHeap.get(l) > maxHeap.get(ma))
ma = l;
if (r < size() && maxHeap.get(r) > maxHeap.get(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
swap(i, ma);
// Loop downwards heapification
// Continue sifting down
i = ma;
}
}
/* Driver Code */
/* Print the heap (binary tree) */
public void print() {
Queue<Integer> queue = new PriorityQueue<>((a, b) -> { return b - a; });
queue.addAll(maxHeap);
@@ -128,32 +128,32 @@ class MaxHeap {
public class my_heap {
public static void main(String[] args) {
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
/* Initialize a max heap */
MaxHeap maxHeap = new MaxHeap(Arrays.asList(9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2));
System.out.println("\nAfter inputting list and building heap");
System.out.println("\nAfter building a heap from the input list:");
maxHeap.print();
/* Check if heap is empty */
/* Get the top element of the heap */
int peek = maxHeap.peek();
System.out.format("\nHeap top element is %d\n", peek);
System.out.format("\nTop element: %d\n", peek);
/* Element enters heap */
/* Push an element onto the heap */
int val = 7;
maxHeap.push(val);
System.out.format("\nAfter element %d enters heap\n", val);
System.out.format("\nAfter pushing %d onto the heap:\n", val);
maxHeap.print();
/* Time complexity is O(n), not O(nlogn) */
/* Pop the top element from the heap */
peek = maxHeap.pop();
System.out.format("\nAfter heap top element %d exits heap\n", peek);
System.out.format("\nAfter popping the top element %d:\n", peek);
maxHeap.print();
/* Get heap size */
/* Get the heap size */
int size = maxHeap.size();
System.out.format("\nHeap element count is %d\n", size);
System.out.format("\nNumber of elements in the heap: %d\n", size);
/* Check if heap is empty */
/* Check whether the heap is empty */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\nHeap is empty %b\n", isEmpty);
System.out.format("\nIs the heap empty? %b\n", isEmpty);
}
}

View File

@@ -10,17 +10,17 @@ import utils.*;
import java.util.*;
public class top_k {
/* Find the largest k elements in array based on heap */
/* Use a heap to find the k largest elements in an array */
static Queue<Integer> topKHeap(int[] nums, int k) {
// Python's heapq module implements min heap by default
// Initialize a min heap
Queue<Integer> heap = new PriorityQueue<Integer>();
// Enter the first k elements of array into heap
// Push the first k array elements onto the heap
for (int i = 0; i < k; i++) {
heap.offer(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 (int 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] > heap.peek()) {
heap.poll();
heap.offer(nums[i]);
@@ -34,7 +34,7 @@ public class top_k {
int k = 3;
Queue<Integer> res = topKHeap(nums, k);
System.out.println("The largest " + k + " elements are");
System.out.println("The largest " + k + " elements are:");
PrintUtil.printHeap(res);
}
}

View File

@@ -7,39 +7,39 @@
package chapter_searching;
public class binary_search {
/* Binary search (closed interval on both sides) */
/* Binary search (closed interval) */
static int binarySearch(int[] nums, int 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
int 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) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) // This means target is in the interval [m+1, j]
if (nums[m] < target) // 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]
else if (nums[m] > target) // In this case, target must be in [i, m-1] if it exists
j = m - 1;
else // Found the target element, return its index
else // The target element was found; return its index
return m;
}
// 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) */
static int binarySearchLCRO(int[] nums, int 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
int 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) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
if (nums[m] < target) // This means target is in the interval [m+1, j)
if (nums[m] < target) // 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)
else if (nums[m] > target) // In this case, target must be in [i, m) if it exists
j = m;
else // Found the target element, return its index
else // The target element was found; return its index
return m;
}
// Target element not found, return -1
// The target element was not found; return -1
return -1;
}
@@ -47,11 +47,11 @@ public class binary_search {
int target = 6;
int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 };
/* Binary search (closed interval on both sides) */
/* Binary search (closed interval) */
int index = binarySearch(nums, target);
System.out.println("Index of target element 6 = " + index);
/* Binary search (left-closed right-open interval) */
/* Binary search (left-closed, right-open interval) */
index = binarySearchLCRO(nums, target);
System.out.println("Index of target element 6 = " + index);
}

View File

@@ -7,43 +7,43 @@
package chapter_searching;
public class binary_search_edge {
/* Binary search for the leftmost target */
/* Find the leftmost occurrence of target using binary search */
static int binarySearchLeftEdge(int[] nums, int target) {
// Equivalent to finding the insertion point of target
// This is equivalent to finding the insertion point of target
int i = binary_search_insertion.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 */
static int binarySearchRightEdge(int[] nums, int target) {
// Convert to finding the leftmost target + 1
// Reduce the problem to finding the leftmost insertion point of target + 1
int i = binary_search_insertion.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
int 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;
}
public static void main(String[] args) {
// Array with duplicate elements
// Array containing duplicate elements
int[] nums = { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 };
System.out.println("\nArray nums = " + java.util.Arrays.toString(nums));
// Binary search left and right boundaries
// Find the left and right boundaries using binary search
for (int target : new int[] { 6, 7 }) {
int index = binarySearchLeftEdge(nums, target);
System.out.println("Index of leftmost element " + target + " is " + index);
System.out.println("Leftmost occurrence of " + target + " has index " + index);
index = binarySearchRightEdge(nums, target);
System.out.println("Index of rightmost element " + target + " is " + index);
System.out.println("Rightmost occurrence of " + target + " has index " + index);
}
}
}

View File

@@ -7,34 +7,34 @@
package chapter_searching;
class binary_search_insertion {
/* Binary search for insertion point (no duplicate elements) */
/* Find an insertion point using binary search (no duplicates) */
static int binarySearchInsertionSimple(int[] nums, int target) {
int i = 0, j = nums.length - 1; // Initialize closed interval [0, n-1]
int i = 0, j = nums.length - 1; // Initialize the closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
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) */
static int binarySearchInsertion(int[] nums, int target) {
int i = 0, j = nums.length - 1; // Initialize closed interval [0, n-1]
int i = 0, j = nums.length - 1; // Initialize the closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
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
@@ -42,22 +42,22 @@ class binary_search_insertion {
}
public static void main(String[] args) {
// Array without duplicate elements
// Array with no duplicate elements
int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 };
System.out.println("\nArray nums = " + java.util.Arrays.toString(nums));
// Binary search for insertion point
// Find an insertion point using binary search
for (int target : new int[] { 6, 9 }) {
int index = binarySearchInsertionSimple(nums, target);
System.out.println("Insertion point index for element " + target + " is " + index);
System.out.println("Element " + target + " has insertion point index " + index);
}
// Array with duplicate elements
// Array containing duplicate elements
nums = new int[] { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 };
System.out.println("\nArray nums = " + java.util.Arrays.toString(nums));
// Binary search for insertion point
// Find an insertion point using binary search
for (int target : new int[] { 2, 6, 20 }) {
int index = binarySearchInsertion(nums, target);
System.out.println("Insertion point index for element " + target + " is " + index);
System.out.println("Element " + target + " has insertion point index " + index);
}
}
}

View File

@@ -10,42 +10,42 @@ import utils.*;
import java.util.*;
public class hashing_search {
/* Hash search (array) */
/* Hash-based search (array) */
static int hashingSearchArray(Map<Integer, Integer> map, int 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.getOrDefault(target, -1);
}
/* Hash search (linked list) */
/* Hash-based search (linked list) */
static ListNode hashingSearchLinkedList(Map<Integer, ListNode> map, int 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 the hash table does not contain this key
return map.getOrDefault(target, null);
}
public static void main(String[] args) {
int target = 3;
/* Hash search (array) */
/* Hash-based search (array) */
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
// Initialize hash table
// Initialize the hash table
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i); // key: element, value: index
map.put(nums[i], i); // key: element; value: index
}
int index = hashingSearchArray(map, target);
System.out.println("Index of target element 3 = " + index);
/* Hash search (linked list) */
/* Hash-based search (linked list) */
ListNode head = ListNode.arrToLinkedList(nums);
// Initialize hash table
// Initialize the hash table
Map<Integer, ListNode> map1 = new HashMap<>();
while (head != null) {
map1.put(head.val, head); // key: node value, value: node
map1.put(head.val, head); // key: node value; value: node
head = head.next;
}
ListNode node = hashingSearchLinkedList(map1, target);
System.out.println("Node object corresponding to target node value 3 is " + node);
System.out.println("The node object corresponding to target value 3 is " + node);
}
}

View File

@@ -11,13 +11,13 @@ import utils.*;
public class linear_search {
/* Linear search (array) */
static int linearSearchArray(int[] nums, int target) {
// Traverse array
// Traverse the array
for (int 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;
}
@@ -25,26 +25,26 @@ public class linear_search {
static ListNode linearSearchLinkedList(ListNode head, int target) {
// Traverse the linked list
while (head != null) {
// 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
// The target node was not found; return null
return null;
}
public static void main(String[] args) {
int target = 3;
/* Perform linear search in array */
/* Perform linear search on the array */
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
int index = linearSearchArray(nums, target);
System.out.println("Index of target element 3 = " + index);
/* Perform linear search in linked list */
/* Perform linear search on the linked list */
ListNode head = ListNode.arrToLinkedList(nums);
ListNode node = linearSearchLinkedList(head, target);
System.out.println("Node object corresponding to target node value 3 is " + node);
System.out.println("The node object corresponding to target value 3 is " + node);
}
}

View File

@@ -9,10 +9,10 @@ package chapter_searching;
import java.util.*;
public class two_sum {
/* Method 1: Brute force enumeration */
/* Method 1: brute-force enumeration */
static int[] twoSumBruteForce(int[] nums, int target) {
int size = nums.length;
// Two nested loops, time complexity is O(n^2)
// Two nested loops give a time complexity of O(n^2)
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target)
@@ -22,12 +22,12 @@ public class two_sum {
return new int[0];
}
/* Method 2: Auxiliary hash table */
/* Method 2: auxiliary hash table */
static int[] twoSumHashTable(int[] nums, int target) {
int size = nums.length;
// Auxiliary hash table, space complexity is O(n)
// The auxiliary hash table uses O(n) space
Map<Integer, Integer> dic = new HashMap<>();
// Single loop, time complexity is O(n)
// A single loop gives a time complexity of O(n)
for (int i = 0; i < size; i++) {
if (dic.containsKey(target - nums[i])) {
return new int[] { dic.get(target - nums[i]), i };
@@ -38,16 +38,16 @@ public class two_sum {
}
public static void main(String[] args) {
// ======= Test Case =======
// ======= Test case =======
int[] nums = { 2, 7, 11, 15 };
int target = 13;
// ====== Driver Code ======
// ====== Driver code ======
// Method 1
int[] res = twoSumBruteForce(nums, target);
System.out.println("Method 1 res = " + Arrays.toString(res));
System.out.println("Method 1: res = " + Arrays.toString(res));
// Method 2
res = twoSumHashTable(nums, target);
System.out.println("Method 2 res = " + Arrays.toString(res));
System.out.println("Method 2: res = " + Arrays.toString(res));
}
}

View File

@@ -11,9 +11,9 @@ import java.util.*;
public class bubble_sort {
/* Bubble sort */
static void bubbleSort(int[] nums) {
// Outer loop: unsorted range is [0, i]
// Outer loop: the unsorted range is [0, i]
for (int 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 (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
@@ -27,31 +27,31 @@ public class bubble_sort {
/* Bubble sort (flag optimization) */
static void bubbleSortWithFlag(int[] nums) {
// Outer loop: unsorted range is [0, i]
// Outer loop: the unsorted range is [0, i]
for (int i = nums.length - 1; i > 0; i--) {
boolean flag = false; // Initialize flag
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
boolean flag = false; // Initialize the flag
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
int 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
break; // Exit immediately if this pass made no swaps
}
}
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
bubbleSort(nums);
System.out.println("After bubble sort completes, nums = " + Arrays.toString(nums));
System.out.println("After bubble sort, nums = " + Arrays.toString(nums));
int[] nums1 = { 4, 1, 3, 1, 5, 2 };
bubbleSortWithFlag(nums1);
System.out.println("After bubble sort completes, nums1 = " + Arrays.toString(nums1));
System.out.println("After bubble sort, nums1 = " + Arrays.toString(nums1));
}
}

View File

@@ -11,25 +11,25 @@ import java.util.*;
public class bucket_sort {
/* Bucket sort */
static void bucketSort(float[] nums) {
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
// Initialize k = n/2 buckets, expecting 2 elements per bucket
int k = nums.length / 2;
List<List<Float>> buckets = new ArrayList<>();
for (int i = 0; i < k; i++) {
buckets.add(new ArrayList<>());
}
// 1. Distribute array elements into various buckets
// 1. Distribute the array elements among the buckets
for (float num : nums) {
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
// The input range is [0, 1); use num * k to map each value to an index in [0, k-1]
int i = (int) (num * k);
// Add num to bucket i
buckets.get(i).add(num);
}
// 2. Sort each bucket
for (List<Float> bucket : 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
Collections.sort(bucket);
}
// 3. Traverse buckets to merge results
// 3. Traverse the buckets to combine the results
int i = 0;
for (List<Float> bucket : buckets) {
for (float num : bucket) {
@@ -39,9 +39,9 @@ public class bucket_sort {
}
public static void main(String[] args) {
// Assume input data is floating point, interval [0, 1)
// Assume the input consists of floating-point numbers in [0, 1)
float[] nums = { 0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f };
bucketSort(nums);
System.out.println("After bucket sort completes, nums = " + Arrays.toString(nums));
System.out.println("After bucket sort, nums = " + Arrays.toString(nums));
}
}

View File

@@ -10,20 +10,20 @@ import java.util.*;
public class counting_sort {
/* Counting sort */
// Simple implementation, cannot be used for sorting objects
// Simple implementation; cannot be used to sort objects
static void countingSortNaive(int[] nums) {
// 1. Count the maximum element m in the array
// 1. Find the maximum array element m
int m = 0;
for (int num : nums) {
m = Math.max(m, num);
}
// 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
int[] counter = new int[m + 1];
for (int num : 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
int i = 0;
for (int num = 0; num < m + 1; num++) {
for (int j = 0; j < counter[num]; j++, i++) {
@@ -33,34 +33,34 @@ public class counting_sort {
}
/* Counting sort */
// Complete implementation, can sort objects and is a stable sort
// Full implementation; stable and adaptable to sorting objects
static void countingSort(int[] nums) {
// 1. Count the maximum element m in the array
// 1. Find the maximum array element m
int m = 0;
for (int num : nums) {
m = Math.max(m, num);
}
// 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
int[] counter = new int[m + 1];
for (int num : 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 (int 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
int n = nums.length;
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int 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 (int i = 0; i < n; i++) {
nums[i] = res[i];
}
@@ -69,10 +69,10 @@ public class counting_sort {
public static void main(String[] args) {
int[] nums = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
countingSortNaive(nums);
System.out.println("After counting sort (cannot sort objects) completes, nums = " + Arrays.toString(nums));
System.out.println("After counting sort (does not support objects), nums = " + Arrays.toString(nums));
int[] nums1 = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
countingSort(nums1);
System.out.println("After counting sort completes, nums1 = " + Arrays.toString(nums1));
System.out.println("After counting sort, nums1 = " + Arrays.toString(nums1));
}
}

View File

@@ -9,10 +9,10 @@ package chapter_sorting;
import java.util.Arrays;
public class heap_sort {
/* Heap length is n, start heapifying node i, from top to bottom */
/* Sift down from node i in a heap of size n */
public static void siftDown(int[] nums, int n, int 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
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
@@ -20,31 +20,31 @@ public class heap_sort {
ma = l;
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
int temp = nums[i];
nums[i] = nums[ma];
nums[ma] = temp;
// Loop downwards heapification
// Continue sifting down
i = ma;
}
}
/* Heap sort */
public static void heapSort(int[] nums) {
// Build heap operation: heapify all nodes except leaves
// Build the heap by sifting down from every non-leaf node
for (int i = 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 (int 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)
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
// Start heapifying the root node, from top to bottom
// Sift down starting at the root
siftDown(nums, i, 0);
}
}
@@ -52,6 +52,6 @@ public class heap_sort {
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
heapSort(nums);
System.out.println("After heap sort completes, nums = " + Arrays.toString(nums));
System.out.println("After heap sort, nums = " + Arrays.toString(nums));
}
}

View File

@@ -11,21 +11,21 @@ import java.util.*;
public class insertion_sort {
/* Insertion sort */
static void insertionSort(int[] nums) {
// Outer loop: sorted interval is [0, i-1]
// Outer loop: the sorted range is [0, i-1]
for (int i = 1; i < nums.length; i++) {
int 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
}
}
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
insertionSort(nums);
System.out.println("After insertion sort completes, nums = " + Arrays.toString(nums));
System.out.println("After insertion sort, nums = " + Arrays.toString(nums));
}
}

View File

@@ -9,14 +9,14 @@ package chapter_sorting;
import java.util.*;
public class merge_sort {
/* Merge left subarray and right subarray */
/* Merge the left and right subarrays */
static void merge(int[] nums, int left, int mid, int 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
int[] tmp = new int[right - left + 1];
// Initialize the start indices of the left and right subarrays
// Initialize the starting indices of the left and right subarrays
int 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++];
@@ -30,7 +30,7 @@ public class merge_sort {
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];
}
@@ -38,14 +38,14 @@ public class merge_sort {
/* Merge sort */
static void mergeSort(int[] nums, int left, int right) {
// Termination condition
// Base case
if (left >= right)
return; // Terminate recursion when subarray length is 1
// Divide and conquer stage
int mid = 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
return; // Stop recursing when the subarray has at most one element
// Divide phase
int mid = 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);
}
@@ -53,6 +53,6 @@ public class merge_sort {
/* Merge sort */
int[] nums = { 7, 3, 2, 6, 0, 1, 5, 4 };
mergeSort(nums, 0, nums.length - 1);
System.out.println("After merge sort completes, nums = " + Arrays.toString(nums));
System.out.println("After merge sort, nums = " + Arrays.toString(nums));
}
}

View File

@@ -10,36 +10,36 @@ import java.util.*;
/* Quick sort class */
class QuickSort {
/* Swap elements */
/* Swap the elements */
static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* Sentinel partition */
/* Two-pointer partitioning */
static int partition(int[] nums, int left, int right) {
// Use nums[left] as the pivot
int 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
j--; // Scan 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
i++; // Scan from left to right for the first element larger than the pivot
swap(nums, i, j); // Swap these two elements
}
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
return i; // Return the pivot index
}
/* Quick sort */
public static void quickSort(int[] nums, int left, int 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
int pivot = partition(nums, left, right);
// Recursively process the left subarray and right subarray
// Recurse on the left and right subarrays
quickSort(nums, left, pivot - 1);
quickSort(nums, pivot + 1, right);
}
@@ -47,7 +47,7 @@ class QuickSort {
/* Quick sort class (median pivot optimization) */
class QuickSortMedian {
/* Swap elements */
/* Swap the elements */
static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
@@ -58,39 +58,39 @@ class QuickSortMedian {
static int medianThree(int[] nums, int left, int mid, int right) {
int l = nums[left], m = nums[mid], r = nums[right];
if ((l <= m && m <= r) || (r <= m && m <= l))
return mid; // m is between l and r
return mid; // m lies between l and r
if ((m <= l && l <= r) || (r <= l && l <= m))
return left; // l is between m and r
return left; // l lies between m and r
return right;
}
/* Sentinel partition (median of three) */
/* Two-pointer partitioning (median of three) */
static int partition(int[] nums, int left, int right) {
// Select the median of three candidate elements
int med = medianThree(nums, left, (left + right) / 2, right);
// Swap the median to the array's leftmost position
// Swap the median into the leftmost position of the current subarray
swap(nums, left, med);
// Use nums[left] as the pivot
int 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
j--; // Scan 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
i++; // Scan from left to right for the first element larger than the pivot
swap(nums, i, j); // Swap these two elements
}
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
return i; // Return the pivot index
}
/* Quick sort */
public static void quickSort(int[] nums, int left, int 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
int pivot = partition(nums, left, right);
// Recursively process the left subarray and right subarray
// Recurse on the left and right subarrays
quickSort(nums, left, pivot - 1);
quickSort(nums, pivot + 1, right);
}
@@ -98,41 +98,41 @@ class QuickSortMedian {
/* Quick sort class (recursion depth optimization) */
class QuickSortTailCall {
/* Swap elements */
/* Swap the elements */
static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* Sentinel partition */
/* Two-pointer partitioning */
static int partition(int[] nums, int left, int right) {
// Use nums[left] as the pivot
int 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
j--; // Scan 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
i++; // Scan from left to right for the first element larger than the pivot
swap(nums, i, j); // Swap these two elements
}
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
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) */
public static void quickSort(int[] nums, int left, int 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
int pivot = 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) {
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 {
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]
}
}
}
@@ -143,16 +143,16 @@ public class quick_sort {
/* Quick sort */
int[] nums = { 2, 4, 1, 0, 3, 5 };
QuickSort.quickSort(nums, 0, nums.length - 1);
System.out.println("After quick sort completes, nums = " + Arrays.toString(nums));
System.out.println("After quick sort, nums = " + Arrays.toString(nums));
/* Quick sort (recursion depth optimization) */
/* Quick sort (median pivot optimization) */
int[] nums1 = { 2, 4, 1, 0, 3, 5 };
QuickSortMedian.quickSort(nums1, 0, nums1.length - 1);
System.out.println("After quick sort (median pivot optimization) completes, nums1 = " + Arrays.toString(nums1));
System.out.println("After quick sort (median pivot optimization), nums1 = " + Arrays.toString(nums1));
/* Quick sort (recursion depth optimization) */
int[] nums2 = { 2, 4, 1, 0, 3, 5 };
QuickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
System.out.println("After quick sort (recursion depth optimization) completes, nums2 = " + Arrays.toString(nums2));
System.out.println("After quick sort (recursion depth optimization), nums2 = " + Arrays.toString(nums2));
}
}

View File

@@ -9,52 +9,52 @@ package chapter_sorting;
import java.util.*;
public class radix_sort {
/* 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) */
static int digit(int num, int exp) {
// Passing exp instead of k can avoid repeated expensive exponentiation here
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
return (num / exp) % 10;
}
/* Counting sort (based on nums k-th digit) */
/* Counting sort (sort nums by the k-th digit) */
static void countingSortDigit(int[] nums, int 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
int[] counter = new int[10];
int n = nums.length;
// Count the occurrence of digits 0~9
// Count the occurrences of each digit from 0 to 9
for (int i = 0; i < n; i++) {
int d = digit(nums[i], exp); // Get the k-th digit of nums[i], noted as d
counter[d]++; // Count the occurrence of digit d
int 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 (int 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
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int d = digit(nums[i], exp);
int j = counter[d] - 1; // Get the index j for d in the array
int 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 (int i = 0; i < n; i++)
nums[i] = res[i];
}
/* Radix sort */
static void radixSort(int[] 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
int m = Integer.MIN_VALUE;
for (int num : nums)
if (num > m)
m = num;
// Traverse from the lowest to the highest digit
// Process digits from least significant to most significant
for (int 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);
}
}
@@ -64,6 +64,6 @@ public class radix_sort {
int[] nums = { 10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996 };
radixSort(nums);
System.out.println("After radix sort completes, nums = " + Arrays.toString(nums));
System.out.println("After radix sort, nums = " + Arrays.toString(nums));
}
}

View File

@@ -12,15 +12,15 @@ public class selection_sort {
/* Selection sort */
public static void selectionSort(int[] nums) {
int n = nums.length;
// Outer loop: unsorted interval is [i, n-1]
// Outer loop: the unsorted range is [i, n-1]
for (int 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
int k = i;
for (int 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
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
@@ -30,6 +30,6 @@ public class selection_sort {
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
selectionSort(nums);
System.out.println("After selection sort completes, nums = " + Arrays.toString(nums));
System.out.println("After selection sort, nums = " + Arrays.toString(nums));
}
}

View File

@@ -8,11 +8,11 @@ package chapter_stack_and_queue;
import java.util.*;
/* Double-ended queue based on circular array implementation */
/* Deque implemented with a circular array */
class ArrayDeque {
private int[] nums; // Array for storing double-ended queue elements
private int front; // Front pointer, points to the front of the queue element
private int queSize; // Double-ended queue length
private int[] nums; // Array that stores the deque elements
private int front; // Front pointer, pointing to the first element
private int queSize; // Deque size
/* Constructor */
public ArrayDeque(int capacity) {
@@ -20,91 +20,91 @@ class ArrayDeque {
front = queSize = 0;
}
/* Get the capacity of the double-ended queue */
/* Get the deque capacity */
public int capacity() {
return nums.length;
}
/* Get the length of the double-ended queue */
/* Get the deque size */
public int size() {
return queSize;
}
/* Check if the double-ended queue is empty */
/* Check whether the deque is empty */
public boolean isEmpty() {
return queSize == 0;
}
/* Calculate circular array index */
/* Calculate an index in the circular array */
private int index(int 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 + capacity()) % capacity();
}
/* Front of the queue enqueue */
/* Enqueue at the front */
public void pushFirst(int num) {
if (queSize == capacity()) {
System.out.println("Double-ended queue is full");
System.out.println("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
front = index(front - 1);
// Add num to front of queue
// Add num to the front
nums[front] = num;
queSize++;
}
/* Rear of the queue enqueue */
/* Enqueue at the rear */
public void pushLast(int num) {
if (queSize == capacity()) {
System.out.println("Double-ended queue is full");
System.out.println("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
int rear = index(front + queSize);
// Front pointer moves one position backward
// Add num to the rear
nums[rear] = num;
queSize++;
}
/* Rear of the queue dequeue */
/* Dequeue from the front */
public int popFirst() {
int num = peekFirst();
// Move front pointer backward by one position
// Advance the front pointer by one position
front = index(front + 1);
queSize--;
return num;
}
/* Access rear of the queue element */
/* Dequeue from the rear */
public int popLast() {
int num = peekLast();
queSize--;
return num;
}
/* Return list for printing */
/* Access the front element */
public int peekFirst() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return nums[front];
}
/* Driver Code */
/* Access the rear element */
public int peekLast() {
if (isEmpty())
throw new IndexOutOfBoundsException();
// Initialize double-ended queue
// Calculate the index of the last element
int last = index(front + queSize - 1);
return nums[last];
}
/* Return array for printing */
/* Return an array for printing */
public int[] toArray() {
// Elements enqueue
// Convert only the list elements within the occupied range
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[index(j)];
@@ -115,37 +115,37 @@ class ArrayDeque {
public class array_deque {
public static void main(String[] args) {
/* Get the length of the double-ended queue */
/* Initialize the deque */
ArrayDeque deque = new ArrayDeque(10);
deque.pushLast(3);
deque.pushLast(2);
deque.pushLast(5);
System.out.println("Double-ended queue deque = " + Arrays.toString(deque.toArray()));
System.out.println("Deque deque = " + Arrays.toString(deque.toArray()));
/* Update element */
/* Access an element */
int peekFirst = deque.peekFirst();
System.out.println("Front element peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("Rear element peekLast = " + peekLast);
/* Elements enqueue */
/* Enqueue elements */
deque.pushLast(4);
System.out.println("After element 4 enqueues at rear, deque = " + Arrays.toString(deque.toArray()));
System.out.println("After enqueuing element 4 at the rear, deque = " + Arrays.toString(deque.toArray()));
deque.pushFirst(1);
System.out.println("After element 1 enqueues at front, deque = " + Arrays.toString(deque.toArray()));
System.out.println("After enqueuing element 1 at the front, deque = " + Arrays.toString(deque.toArray()));
/* Element dequeue */
/* Dequeue an element */
int popLast = deque.popLast();
System.out.println("Rear dequeue element = " + popLast + ", after rear dequeue, deque = " + Arrays.toString(deque.toArray()));
System.out.println("Element dequeued from the rear = " + popLast + ", after dequeuing from the rear, deque = " + Arrays.toString(deque.toArray()));
int popFirst = deque.popFirst();
System.out.println("Front dequeue element = " + popFirst + ", after front dequeue, deque = " + Arrays.toString(deque.toArray()));
System.out.println("Element dequeued from the front = " + popFirst + ", after dequeuing from the front, deque = " + Arrays.toString(deque.toArray()));
/* Get the length of the double-ended queue */
/* Get the deque size */
int size = deque.size();
System.out.println("Double-ended queue length size = " + size);
System.out.println("Deque size = " + size);
/* Check if the double-ended queue is empty */
/* Check whether the deque is empty */
boolean isEmpty = deque.isEmpty();
System.out.println("Double-ended queue is empty = " + isEmpty);
System.out.println("Is the deque empty = " + isEmpty);
}
}

View File

@@ -8,28 +8,28 @@ package chapter_stack_and_queue;
import java.util.*;
/* Queue based on circular array implementation */
/* Queue implemented with a circular array */
class ArrayQueue {
private int[] nums; // Array for storing queue elements
private int front; // Front pointer, points to the front of the queue element
private int queSize; // Queue length
private int[] nums; // Array that stores the queue elements
private int front; // Front pointer, pointing to the first element
private int queSize; // Queue size
public ArrayQueue(int capacity) {
nums = new int[capacity];
front = queSize = 0;
}
/* Get the capacity of the queue */
/* Get the queue capacity */
public int capacity() {
return nums.length;
}
/* Get the length of the queue */
/* Get the queue size */
public int size() {
return queSize;
}
/* Check if the queue is empty */
/* Check whether the queue is empty */
public boolean isEmpty() {
return queSize == 0;
}
@@ -40,10 +40,10 @@ class ArrayQueue {
System.out.println("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
int rear = (front + queSize) % capacity();
// Front pointer moves one position backward
// Add num to the rear
nums[rear] = num;
queSize++;
}
@@ -51,22 +51,22 @@ class ArrayQueue {
/* Dequeue */
public int pop() {
int num = 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
front = (front + 1) % capacity();
queSize--;
return num;
}
/* Return list for printing */
/* Access the front element */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return nums[front];
}
/* Return array */
/* Return an array */
public int[] toArray() {
// Elements enqueue
// Convert only the list elements within the occupied range
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[j % capacity()];
@@ -77,11 +77,11 @@ class ArrayQueue {
public class array_queue {
public static void main(String[] args) {
/* Access front of the queue element */
/* Initialize the queue */
int capacity = 10;
ArrayQueue queue = new ArrayQueue(capacity);
/* Elements enqueue */
/* Enqueue elements */
queue.push(1);
queue.push(3);
queue.push(2);
@@ -89,27 +89,27 @@ public class array_queue {
queue.push(4);
System.out.println("Queue queue = " + Arrays.toString(queue.toArray()));
/* Return list for printing */
/* Access the front element */
int peek = queue.peek();
System.out.println("Front element peek = " + peek);
/* Element dequeue */
/* Dequeue an element */
int pop = queue.pop();
System.out.println("Dequeue element pop = " + pop + ", after dequeue, queue = " + Arrays.toString(queue.toArray()));
System.out.println("Dequeued element pop = " + pop + ", after dequeuing, queue = " + Arrays.toString(queue.toArray()));
/* Get the length of the queue */
/* Get the queue size */
int size = queue.size();
System.out.println("Queue length size = " + size);
System.out.println("Queue size = " + size);
/* Check if the queue is empty */
/* Check whether the queue is empty */
boolean isEmpty = queue.isEmpty();
System.out.println("Queue is empty = " + isEmpty);
System.out.println("Is the queue empty = " + isEmpty);
/* Test circular array */
/* Test the circular array */
for (int i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
System.out.println("After round " + i + " enqueue + dequeue, queue = " + Arrays.toString(queue.toArray()));
System.out.println("Round " + i + " : after enqueue + dequeue, queue = " + Arrays.toString(queue.toArray()));
}
}
}

View File

@@ -8,21 +8,21 @@ package chapter_stack_and_queue;
import java.util.*;
/* Stack based on array implementation */
/* Stack implemented with an array */
class ArrayStack {
private ArrayList<Integer> stack;
public ArrayStack() {
// Initialize list (dynamic array)
// Initialize the list (dynamic array)
stack = new ArrayList<>();
}
/* Get the length of the stack */
/* Get the stack size */
public int size() {
return stack.size();
}
/* Check if the stack is empty */
/* Check whether the stack is empty */
public boolean isEmpty() {
return size() == 0;
}
@@ -39,14 +39,14 @@ class ArrayStack {
return stack.remove(size() - 1);
}
/* Return list for printing */
/* Access the top element */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return stack.get(size() - 1);
}
/* Convert List to Array and return */
/* Convert the list to an array and return it */
public Object[] toArray() {
return stack.toArray();
}
@@ -54,10 +54,10 @@ class ArrayStack {
public class array_stack {
public static void main(String[] args) {
/* Access top of the stack element */
/* Initialize the stack */
ArrayStack stack = new ArrayStack();
/* Elements push onto stack */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -65,20 +65,20 @@ public class array_stack {
stack.push(4);
System.out.println("Stack stack = " + Arrays.toString(stack.toArray()));
/* Return list for printing */
/* Access the top element */
int peek = stack.peek();
System.out.println("Stack top element peek = " + peek);
System.out.println("Top element peek = " + peek);
/* Element pop from stack */
/* Pop an element from the stack */
int pop = stack.pop();
System.out.println("Pop element pop = " + pop + ", after pop, stack = " + Arrays.toString(stack.toArray()));
System.out.println("Popped element pop = " + pop + ", after popping, stack = " + Arrays.toString(stack.toArray()));
/* Get the length of the stack */
/* Get the stack size */
int size = stack.size();
System.out.println("Stack length size = " + size);
System.out.println("Stack size = " + size);
/* Check if empty */
/* Check whether it is empty */
boolean isEmpty = stack.isEmpty();
System.out.println("Stack is empty = " + isEmpty);
System.out.println("Is the stack empty = " + isEmpty);
}
}

View File

@@ -10,37 +10,37 @@ import java.util.*;
public class deque {
public static void main(String[] args) {
/* Get the length of the double-ended queue */
/* Initialize the deque */
Deque<Integer> deque = new LinkedList<>();
deque.offerLast(3);
deque.offerLast(2);
deque.offerLast(5);
System.out.println("Double-ended queue deque = " + deque);
System.out.println("Deque deque = " + deque);
/* Update element */
/* Access an element */
int peekFirst = deque.peekFirst();
System.out.println("Front element peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("Rear element peekLast = " + peekLast);
/* Elements enqueue */
/* Enqueue elements */
deque.offerLast(4);
System.out.println("After element 4 enqueues at rear, deque = " + deque);
System.out.println("After enqueuing element 4 at the rear, deque = " + deque);
deque.offerFirst(1);
System.out.println("After element 1 enqueues at front, deque = " + deque);
System.out.println("After enqueuing element 1 at the front, deque = " + deque);
/* Element dequeue */
/* Dequeue an element */
int popLast = deque.pollLast();
System.out.println("Rear dequeue element = " + popLast + ", after rear dequeue, deque = " + deque);
System.out.println("Element dequeued from the rear = " + popLast + ", after dequeuing from the rear, deque = " + deque);
int popFirst = deque.pollFirst();
System.out.println("Front dequeue element = " + popFirst + ", after front dequeue, deque = " + deque);
System.out.println("Element dequeued from the front = " + popFirst + ", after dequeuing from the front, deque = " + deque);
/* Get the length of the double-ended queue */
/* Get the deque size */
int size = deque.size();
System.out.println("Double-ended queue length size = " + size);
System.out.println("Deque size = " + size);
/* Check if the double-ended queue is empty */
/* Check whether the deque is empty */
boolean isEmpty = deque.isEmpty();
System.out.println("Double-ended queue is empty = " + isEmpty);
System.out.println("Is the deque empty = " + isEmpty);
}
}

View File

@@ -11,8 +11,8 @@ import java.util.*;
/* Doubly linked list node */
class ListNode {
int val; // Node value
ListNode next; // Successor node reference
ListNode prev; // Predecessor node reference
ListNode next; // Reference to the next node
ListNode prev; // Reference to the previous node
ListNode(int val) {
this.val = val;
@@ -20,21 +20,21 @@ class ListNode {
}
}
/* Double-ended queue based on doubly linked list implementation */
/* Deque implemented with a doubly linked list */
class LinkedListDeque {
private ListNode front, rear; // Head node front, tail node rear
private int queSize = 0; // Length of the double-ended queue
private ListNode front, rear; // Head node front and tail node rear
private int queSize = 0; // Deque size
public LinkedListDeque() {
front = rear = null;
}
/* Get the length of the double-ended queue */
/* Get the deque size */
public int size() {
return queSize;
}
/* Check if the double-ended queue is empty */
/* Check whether the deque is empty */
public boolean isEmpty() {
return size() == 0;
}
@@ -45,28 +45,28 @@ class LinkedListDeque {
// If the linked list is empty, make both front and rear point to node
if (isEmpty())
front = rear = node;
// Front of the queue enqueue operation
// Enqueue at the front
else if (isFront) {
// Add node to the head of the linked list
front.prev = node;
node.next = front;
front = node; // Update head node
// Rear of the queue enqueue operation
front = node; // Update the head node
// Enqueue at the rear
} else {
// Add node to the tail of the linked list
rear.next = node;
node.prev = rear;
rear = node; // Update tail node
rear = node; // Update the tail node
}
queSize++; // Update queue length
queSize++; // Update the queue size
}
/* Front of the queue enqueue */
/* Enqueue at the front */
public void pushFirst(int num) {
push(num, true);
}
/* Rear of the queue enqueue */
/* Enqueue at the rear */
public void pushLast(int num) {
push(num, false);
}
@@ -76,58 +76,58 @@ class LinkedListDeque {
if (isEmpty())
throw new IndexOutOfBoundsException();
int val;
// 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 (queSize == 1) {
val = front.val;
front = null;
rear = null;
}
// Temporarily store head node value
// Dequeue from the front
else if (isFront) {
val = front.val; // Delete head node
// Delete head node
val = front.val; // Save the head node value
// Remove the head node
ListNode fNext = front.next;
fNext.prev = null;
front.next = null;
front = fNext; // Update head node
// Temporarily store tail node value
front = fNext; // Update the head node
// Dequeue from the rear
} else {
val = rear.val; // Delete tail node
// Update tail node
val = rear.val; // Save the tail node value
// Remove the tail node
ListNode rPrev = rear.prev;
rPrev.next = null;
rear.prev = null;
rear = rPrev; // Update tail node
rear = rPrev; // Update the tail node
}
queSize--; // Update queue length
queSize--; // Update the queue size
return val;
}
/* Rear of the queue dequeue */
/* Dequeue from the front */
public int popFirst() {
return pop(true);
}
/* Access rear of the queue element */
/* Dequeue from the rear */
public int popLast() {
return pop(false);
}
/* Return list for printing */
/* Access the front element */
public int peekFirst() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return front.val;
}
/* Driver Code */
/* Access the rear element */
public int peekLast() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return rear.val;
}
/* Return array for printing */
/* Return an array for printing */
public int[] toArray() {
ListNode node = front;
int[] res = new int[size()];
@@ -141,37 +141,37 @@ class LinkedListDeque {
public class linkedlist_deque {
public static void main(String[] args) {
/* Get the length of the double-ended queue */
/* Initialize the deque */
LinkedListDeque deque = new LinkedListDeque();
deque.pushLast(3);
deque.pushLast(2);
deque.pushLast(5);
System.out.println("Double-ended queue deque = " + Arrays.toString(deque.toArray()));
System.out.println("Deque deque = " + Arrays.toString(deque.toArray()));
/* Update element */
/* Access an element */
int peekFirst = deque.peekFirst();
System.out.println("Front element peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("Rear element peekLast = " + peekLast);
/* Elements enqueue */
/* Enqueue elements */
deque.pushLast(4);
System.out.println("After element 4 enqueues at rear, deque = " + Arrays.toString(deque.toArray()));
System.out.println("After enqueuing element 4 at the rear, deque = " + Arrays.toString(deque.toArray()));
deque.pushFirst(1);
System.out.println("After element 1 enqueues at front, deque = " + Arrays.toString(deque.toArray()));
System.out.println("After enqueuing element 1 at the front, deque = " + Arrays.toString(deque.toArray()));
/* Element dequeue */
/* Dequeue an element */
int popLast = deque.popLast();
System.out.println("Rear dequeue element = " + popLast + ", after rear dequeue, deque = " + Arrays.toString(deque.toArray()));
System.out.println("Element dequeued from the rear = " + popLast + ", after dequeuing from the rear, deque = " + Arrays.toString(deque.toArray()));
int popFirst = deque.popFirst();
System.out.println("Front dequeue element = " + popFirst + ", after front dequeue, deque = " + Arrays.toString(deque.toArray()));
System.out.println("Element dequeued from the front = " + popFirst + ", after dequeuing from the front, deque = " + Arrays.toString(deque.toArray()));
/* Get the length of the double-ended queue */
/* Get the deque size */
int size = deque.size();
System.out.println("Double-ended queue length size = " + size);
System.out.println("Deque size = " + size);
/* Check if the double-ended queue is empty */
/* Check whether the deque is empty */
boolean isEmpty = deque.isEmpty();
System.out.println("Double-ended queue is empty = " + isEmpty);
System.out.println("Is the deque empty = " + isEmpty);
}
}

View File

@@ -8,9 +8,9 @@ package chapter_stack_and_queue;
import java.util.*;
/* Queue based on linked list implementation */
/* Queue implemented with a linked list */
class LinkedListQueue {
private ListNode front, rear; // Head node front, tail node rear
private ListNode front, rear; // Head node front and tail node rear
private int queSize = 0;
public LinkedListQueue() {
@@ -18,12 +18,12 @@ class LinkedListQueue {
rear = null;
}
/* Get the length of the queue */
/* Get the queue size */
public int size() {
return queSize;
}
/* Check if the queue is empty */
/* Check whether the queue is empty */
public boolean isEmpty() {
return size() == 0;
}
@@ -32,11 +32,11 @@ class LinkedListQueue {
public void push(int num) {
// Add num after the tail node
ListNode 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 (front == null) {
front = node;
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 {
rear.next = node;
rear = node;
@@ -47,20 +47,20 @@ class LinkedListQueue {
/* Dequeue */
public int pop() {
int num = peek();
// Delete head node
// Remove the head node
front = front.next;
queSize--;
return num;
}
/* Return list for printing */
/* Access the front element */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return front.val;
}
/* Convert linked list to Array and return */
/* Convert the linked list to an array and return it */
public int[] toArray() {
ListNode node = front;
int[] res = new int[size()];
@@ -74,10 +74,10 @@ class LinkedListQueue {
public class linkedlist_queue {
public static void main(String[] args) {
/* Access front of the queue element */
/* Initialize the queue */
LinkedListQueue queue = new LinkedListQueue();
/* Elements enqueue */
/* Enqueue elements */
queue.push(1);
queue.push(3);
queue.push(2);
@@ -85,20 +85,20 @@ public class linkedlist_queue {
queue.push(4);
System.out.println("Queue queue = " + Arrays.toString(queue.toArray()));
/* Return list for printing */
/* Access the front element */
int peek = queue.peek();
System.out.println("Front element peek = " + peek);
/* Element dequeue */
/* Dequeue an element */
int pop = queue.pop();
System.out.println("Dequeue element pop = " + pop + ", after dequeue, queue = " + Arrays.toString(queue.toArray()));
System.out.println("Dequeued element pop = " + pop + ", after dequeuing, queue = " + Arrays.toString(queue.toArray()));
/* Get the length of the queue */
/* Get the queue size */
int size = queue.size();
System.out.println("Queue length size = " + size);
System.out.println("Queue size = " + size);
/* Check if the queue is empty */
/* Check whether the queue is empty */
boolean isEmpty = queue.isEmpty();
System.out.println("Queue is empty = " + isEmpty);
System.out.println("Is the queue empty = " + isEmpty);
}
}

View File

@@ -9,21 +9,21 @@ package chapter_stack_and_queue;
import java.util.*;
import utils.*;
/* Stack based on linked list implementation */
/* Stack implemented with a linked list */
class LinkedListStack {
private ListNode stackPeek; // Use head node as stack top
private int stkSize = 0; // Stack length
private ListNode stackPeek; // Use the head node as the stack top
private int stkSize = 0; // Stack size
public LinkedListStack() {
stackPeek = null;
}
/* Get the length of the stack */
/* Get the stack size */
public int size() {
return stkSize;
}
/* Check if the stack is empty */
/* Check whether the stack is empty */
public boolean isEmpty() {
return size() == 0;
}
@@ -44,14 +44,14 @@ class LinkedListStack {
return num;
}
/* Return list for printing */
/* Access the top element */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return stackPeek.val;
}
/* Convert List to Array and return */
/* Convert the list to an array and return it */
public int[] toArray() {
ListNode node = stackPeek;
int[] res = new int[size()];
@@ -65,10 +65,10 @@ class LinkedListStack {
public class linkedlist_stack {
public static void main(String[] args) {
/* Access top of the stack element */
/* Initialize the stack */
LinkedListStack stack = new LinkedListStack();
/* Elements push onto stack */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -76,20 +76,20 @@ public class linkedlist_stack {
stack.push(4);
System.out.println("Stack stack = " + Arrays.toString(stack.toArray()));
/* Return list for printing */
/* Access the top element */
int peek = stack.peek();
System.out.println("Stack top element peek = " + peek);
System.out.println("Top element peek = " + peek);
/* Element pop from stack */
/* Pop an element from the stack */
int pop = stack.pop();
System.out.println("Pop element pop = " + pop + ", after pop, stack = " + Arrays.toString(stack.toArray()));
System.out.println("Popped element pop = " + pop + ", after popping, stack = " + Arrays.toString(stack.toArray()));
/* Get the length of the stack */
/* Get the stack size */
int size = stack.size();
System.out.println("Stack length size = " + size);
System.out.println("Stack size = " + size);
/* Check if empty */
/* Check whether it is empty */
boolean isEmpty = stack.isEmpty();
System.out.println("Stack is empty = " + isEmpty);
System.out.println("Is the stack empty = " + isEmpty);
}
}

View File

@@ -10,10 +10,10 @@ import java.util.*;
public class queue {
public static void main(String[] args) {
/* Access front of the queue element */
/* Initialize the queue */
Queue<Integer> queue = new LinkedList<>();
/* Elements enqueue */
/* Enqueue elements */
queue.offer(1);
queue.offer(3);
queue.offer(2);
@@ -21,20 +21,20 @@ public class queue {
queue.offer(4);
System.out.println("Queue queue = " + queue);
/* Return list for printing */
/* Access the front element */
int peek = queue.peek();
System.out.println("Front element peek = " + peek);
/* Element dequeue */
/* Dequeue an element */
int pop = queue.poll();
System.out.println("Dequeue element pop = " + pop + ", after dequeue, queue = " + queue);
System.out.println("Dequeued element pop = " + pop + ", after dequeuing, queue = " + queue);
/* Get the length of the queue */
/* Get the queue size */
int size = queue.size();
System.out.println("Queue length size = " + size);
System.out.println("Queue size = " + size);
/* Check if the queue is empty */
/* Check whether the queue is empty */
boolean isEmpty = queue.isEmpty();
System.out.println("Queue is empty = " + isEmpty);
System.out.println("Is the queue empty = " + isEmpty);
}
}

View File

@@ -10,10 +10,10 @@ import java.util.*;
public class stack {
public static void main(String[] args) {
/* Access top of the stack element */
/* Initialize the stack */
Stack<Integer> stack = new Stack<>();
/* Elements push onto stack */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -21,20 +21,20 @@ public class stack {
stack.push(4);
System.out.println("Stack stack = " + stack);
/* Return list for printing */
/* Access the top element */
int peek = stack.peek();
System.out.println("Stack top element peek = " + peek);
System.out.println("Top element peek = " + peek);
/* Element pop from stack */
/* Pop an element from the stack */
int pop = stack.pop();
System.out.println("Pop element pop = " + pop + ", after pop, stack = " + stack);
System.out.println("Popped element pop = " + pop + ", after popping, stack = " + stack);
/* Get the length of the stack */
/* Get the stack size */
int size = stack.size();
System.out.println("Stack length size = " + size);
System.out.println("Stack size = " + size);
/* Check if empty */
/* Check whether it is empty */
boolean isEmpty = stack.isEmpty();
System.out.println("Stack is empty = " + isEmpty);
System.out.println("Is the stack empty = " + isEmpty);
}
}

View File

@@ -9,7 +9,7 @@ package chapter_tree;
import utils.*;
import java.util.*;
/* Binary tree class represented by array */
/* Binary tree class using an array representation */
class ArrayBinaryTree {
private List<Integer> tree;
@@ -18,30 +18,30 @@ class ArrayBinaryTree {
tree = new ArrayList<>(arr);
}
/* List capacity */
/* List size */
public int size() {
return tree.size();
}
/* Get value of node at index i */
/* Get the value of the node at index i */
public Integer val(int i) {
// If index out of bounds, return null to represent empty position
// If the index is out of bounds, return null to represent an empty position
if (i < 0 || i >= size())
return null;
return tree.get(i);
}
/* Get index of left child node of node at index i */
/* Get the left child index of the node at index i */
public Integer left(int 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 */
public Integer right(int 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 */
public Integer parent(int i) {
return (i - 1) / 2;
}
@@ -49,7 +49,7 @@ class ArrayBinaryTree {
/* Level-order traversal */
public List<Integer> levelOrder() {
List<Integer> res = new ArrayList<>();
// Traverse array directly
// Traverse the array directly
for (int i = 0; i < size(); i++) {
if (val(i) != null)
res.add(val(i));
@@ -59,7 +59,7 @@ class ArrayBinaryTree {
/* Depth-first traversal */
private void dfs(Integer i, String order, List<Integer> res) {
// If empty position, return
// Return if this position is empty
if (val(i) == null)
return;
// Preorder traversal
@@ -99,38 +99,38 @@ class ArrayBinaryTree {
public class array_binary_tree {
public static void main(String[] args) {
// Initialize binary tree
// Here we use a function to generate a binary tree directly from an array
// Initialize the binary tree
// Use a helper function that builds a binary tree directly from an array
List<Integer> arr = Arrays.asList(1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15);
TreeNode root = TreeNode.listToTree(arr);
System.out.println("\nInitialize binary tree\n");
System.out.println("Array representation of binary tree:");
System.out.println("\nInitialize the binary tree\n");
System.out.println("Array representation of the binary tree:");
System.out.println(arr);
System.out.println("Linked list representation of binary tree:");
System.out.println("Linked representation of the binary tree:");
PrintUtil.printTree(root);
// Binary tree class represented by array
// Binary tree class using an array representation
ArrayBinaryTree abt = new ArrayBinaryTree(arr);
// Access node
// Access a node
int i = 1;
Integer l = abt.left(i);
Integer r = abt.right(i);
Integer p = abt.parent(i);
System.out.println("\nCurrent node index is " + i + ", value is " + abt.val(i));
System.out.println("Its left child node index is " + l + ", value is " + (l == null ? "null" : abt.val(l)));
System.out.println("Its right child node index is " + r + ", value is " + (r == null ? "null" : abt.val(r)));
System.out.println("Its parent node index is " + p + ", value is " + (p == null ? "null" : abt.val(p)));
System.out.println("\nCurrent node index: " + i + " with value " + abt.val(i));
System.out.println("Left child index: " + l + " with value " + (l == null ? "null" : abt.val(l)));
System.out.println("Right child index: " + r + " with value " + (r == null ? "null" : abt.val(r)));
System.out.println("Parent index: " + p + " with value " + (p == null ? "null" : abt.val(p)));
// Traverse tree
// Traverse the tree
List<Integer> res = abt.levelOrder();
System.out.println("\nLevel-order traversal is:" + res);
System.out.println("\nLevel-order traversal:" + res);
res = abt.preOrder();
System.out.println("Preorder traversal is:" + res);
System.out.println("Preorder traversal:" + res);
res = abt.inOrder();
System.out.println("Inorder traversal is:" + res);
System.out.println("Inorder traversal:" + res);
res = abt.postOrder();
System.out.println("Postorder traversal is:" + res);
System.out.println("Postorder traversal:" + res);
}
}

View File

@@ -12,118 +12,118 @@ import utils.*;
class AVLTree {
TreeNode root; // Root node
/* Get node height */
/* Get the node height */
public int height(TreeNode 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 */
private void updateHeight(TreeNode 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(height(node.left), height(node.right)) + 1;
}
/* Get balance factor */
/* Get the balance factor */
public int balanceFactor(TreeNode 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 height(node.left) - height(node.right);
}
/* Right rotation operation */
/* Right rotation */
private TreeNode rightRotate(TreeNode node) {
TreeNode child = node.left;
TreeNode 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
updateHeight(node);
updateHeight(child);
// Return root node of subtree after rotation
// Return the root of the rotated subtree
return child;
}
/* Left rotation operation */
/* Left rotation */
private TreeNode leftRotate(TreeNode node) {
TreeNode child = node.right;
TreeNode 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
updateHeight(node);
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 */
private TreeNode rotate(TreeNode node) {
// Get balance factor of node
// Get the balance factor of node
int balanceFactor = balanceFactor(node);
// Left-leaning tree
// Left-heavy tree
if (balanceFactor > 1) {
if (balanceFactor(node.left) >= 0) {
// Right rotation
// Rotate right
return rightRotate(node);
} else {
// First left rotation then right rotation
// Rotate left, then right
node.left = leftRotate(node.left);
return rightRotate(node);
}
}
// Right-leaning tree
// Right-heavy tree
if (balanceFactor < -1) {
if (balanceFactor(node.right) <= 0) {
// Left rotation
// Rotate left
return leftRotate(node);
} else {
// First right rotation then left rotation
// Rotate right, then left
node.right = rightRotate(node.right);
return leftRotate(node);
}
}
// Balanced tree, no rotation needed, return directly
// The tree is balanced; return without rotating
return node;
}
/* Insert node */
/* Insert a node */
public void insert(int val) {
root = insertHelper(root, val);
}
/* Recursively insert node (helper method) */
/* Insert a node recursively (helper method) */
private TreeNode insertHelper(TreeNode node, int 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 = insertHelper(node.left, val);
else if (val > node.val)
node.right = insertHelper(node.right, val);
else
return node; // Duplicate node not inserted, return directly
updateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to this subtree */
return node; // Return without inserting a duplicate node
updateHeight(node); // Update the node height
/* 2. Perform rotations to restore balance in this subtree */
node = rotate(node);
// Return root node of subtree
// Return the subtree root
return node;
}
/* Remove node */
/* Remove a node */
public void remove(int val) {
root = removeHelper(root, val);
}
/* Recursively delete node (helper method) */
/* Remove a node recursively (helper method) */
private TreeNode removeHelper(TreeNode node, int val) {
if (node == null)
return null;
/* 1. Find node and delete */
/* 1. Find and remove the node */
if (val < node.val)
node.left = removeHelper(node.left, val);
else if (val > node.val)
@@ -131,14 +131,14 @@ class AVLTree {
else {
if (node.left == null || node.right == null) {
TreeNode 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
TreeNode temp = node.right;
while (temp.left != null) {
temp = temp.left;
@@ -147,29 +147,29 @@ class AVLTree {
node.val = temp.val;
}
}
updateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to this subtree */
updateHeight(node); // Update the node height
/* 2. Perform rotations to restore balance in this subtree */
node = rotate(node);
// Return root node of subtree
// Return the subtree root
return node;
}
/* Search node */
/* Find a node */
public TreeNode search(int val) {
TreeNode cur = 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;
}
}
@@ -177,22 +177,22 @@ class AVLTree {
public class avl_tree {
static void testInsert(AVLTree tree, int val) {
tree.insert(val);
System.out.println("\nAfter inserting node " + val + ", AVL tree is");
System.out.println("\nAfter inserting node " + val + " the AVL tree is:");
PrintUtil.printTree(tree.root);
}
static void testRemove(AVLTree tree, int val) {
tree.remove(val);
System.out.println("\nAfter removing node " + val + ", AVL tree is");
System.out.println("\nAfter removing node " + val + " the AVL tree is:");
PrintUtil.printTree(tree.root);
}
public static void main(String[] args) {
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
/* Initialize an empty AVL tree */
AVLTree 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);
@@ -204,17 +204,17 @@ public class avl_tree {
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 */
TreeNode node = avlTree.search(7);
System.out.println("\nFound node object is " + node + ", node value = " + node.val);
System.out.println("\nFound node object: " + node + ", node value = " + node.val);
}
}

View File

@@ -14,56 +14,56 @@ class BinarySearchTree {
/* Constructor */
public BinarySearchTree() {
// Initialize empty tree
// Initialize an empty tree
root = null;
}
/* Get binary tree root node */
/* Get the root of the binary tree */
public TreeNode getRoot() {
return root;
}
/* Search node */
/* Find a node */
public TreeNode search(int num) {
TreeNode cur = 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 */
public void insert(int num) {
// If tree is empty, initialize root node
// If the tree is empty, initialize the root node
if (root == null) {
root = new TreeNode(num);
return;
}
TreeNode cur = 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
TreeNode node = new TreeNode(num);
if (pre.val < num)
pre.right = node;
@@ -71,53 +71,53 @@ class BinarySearchTree {
pre.left = node;
}
/* Remove node */
/* Remove a node */
public void remove(int num) {
// If tree is empty, return directly
// Return immediately if the tree is empty
if (root == null)
return;
TreeNode cur = 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
TreeNode child = cur.left != null ? cur.left : cur.right;
// Delete node cur
// Remove node cur
if (cur != 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
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
TreeNode tmp = cur.right;
while (tmp.left != null) {
tmp = tmp.left;
}
// Recursively delete node tmp
// Recursively remove node tmp
remove(tmp.val);
// Replace cur with tmp
// Replace the value of cur with the value of tmp
cur.val = tmp.val;
}
}
@@ -125,34 +125,34 @@ class BinarySearchTree {
public class binary_search_tree {
public static void main(String[] args) {
/* Initialize binary search tree */
/* Initialize the binary search tree */
BinarySearchTree 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
int[] nums = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 };
for (int num : nums) {
bst.insert(num);
}
System.out.println("\nInitialized binary tree is\n");
System.out.println("\nThe initialized binary tree is:\n");
PrintUtil.printTree(bst.getRoot());
/* Search node */
/* Find a node */
TreeNode node = bst.search(7);
System.out.println("\nFound node object is " + node + ", node value = " + node.val);
System.out.println("\nFound node object: " + node + ", node value = " + node.val);
/* Insert node */
/* Insert a node */
bst.insert(16);
System.out.println("\nAfter inserting node 16, binary tree is\n");
System.out.println("\nBinary tree after inserting node 16:\n");
PrintUtil.printTree(bst.getRoot());
/* Remove node */
/* Remove a node */
bst.remove(1);
System.out.println("\nAfter removing node 1, binary tree is\n");
System.out.println("\nBinary tree after removing node 1:\n");
PrintUtil.printTree(bst.getRoot());
bst.remove(2);
System.out.println("\nAfter removing node 2, binary tree is\n");
System.out.println("\nBinary tree after removing node 2:\n");
PrintUtil.printTree(bst.getRoot());
bst.remove(4);
System.out.println("\nAfter removing node 4, binary tree is\n");
System.out.println("\nBinary tree after removing node 4:\n");
PrintUtil.printTree(bst.getRoot());
}
}

View File

@@ -10,31 +10,31 @@ import utils.*;
public class binary_tree {
public static void main(String[] args) {
/* Initialize binary tree */
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Build references (pointers) between nodes
// Set up references (pointers) between the nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
System.out.println("\nInitialize binary tree\n");
System.out.println("\nInitialize the binary tree\n");
PrintUtil.printTree(n1);
/* Insert node P between n1 -> n2 */
/* Insert and remove nodes */
TreeNode P = new TreeNode(0);
// Delete node
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P;
P.left = n2;
System.out.println("\nAfter inserting node P\n");
System.out.println("\nAfter inserting node P:\n");
PrintUtil.printTree(n1);
// Remove node P
n1.left = n2;
System.out.println("\nAfter removing node P\n");
System.out.println("\nAfter removing node P:\n");
PrintUtil.printTree(n1);
}
}

View File

@@ -12,31 +12,31 @@ import java.util.*;
public class binary_tree_bfs {
/* Level-order traversal */
static List<Integer> levelOrder(TreeNode root) {
// Initialize queue, add root node
// Initialize a queue and enqueue the root
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// Initialize a list to save the traversal sequence
// Initialize a list to store the traversal sequence
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // Dequeue
list.add(node.val); // Save node value
TreeNode node = queue.poll(); // Dequeue from the queue
list.add(node.val); // Store the node value
if (node.left != null)
queue.offer(node.left); // Left child node enqueue
queue.offer(node.left); // Enqueue the left child
if (node.right != null)
queue.offer(node.right); // Right child node enqueue
queue.offer(node.right); // Enqueue the right child
}
return list;
}
public static void main(String[] args) {
/* Initialize binary tree */
// Here we use a function to generate a binary tree directly from an array
/* Initialize the binary tree */
// Use a helper function that builds a binary tree directly from an array
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree\n");
System.out.println("\nInitialize the binary tree\n");
PrintUtil.printTree(root);
/* Level-order traversal */
List<Integer> list = levelOrder(root);
System.out.println("\nLevel-order traversal node print sequence = " + list);
System.out.println("\nNode sequence from level-order traversal = " + list);
}
}

View File

@@ -10,14 +10,14 @@ import utils.*;
import java.util.*;
public class binary_tree_dfs {
// Initialize list for storing traversal sequence
// Initialize a list to store the traversal sequence
static ArrayList<Integer> list = new ArrayList<>();
/* Preorder traversal */
static void preOrder(TreeNode root) {
if (root == null)
return;
// Visit priority: root node -> left subtree -> right subtree
// Visit order: root -> left subtree -> right subtree
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
@@ -27,7 +27,7 @@ public class binary_tree_dfs {
static void inOrder(TreeNode root) {
if (root == null)
return;
// Visit priority: left subtree -> root node -> right subtree
// Visit order: left subtree -> root -> right subtree
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
@@ -37,32 +37,32 @@ public class binary_tree_dfs {
static void postOrder(TreeNode 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.add(root.val);
}
public static void main(String[] args) {
/* Initialize binary tree */
// Here we use a function to generate a binary tree directly from an array
/* Initialize the binary tree */
// Use a helper function that builds a binary tree directly from an array
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println("\nInitialize binary tree\n");
System.out.println("\nInitialize the binary tree\n");
PrintUtil.printTree(root);
/* Preorder traversal */
list.clear();
preOrder(root);
System.out.println("\nPreorder traversal node print sequence = " + list);
System.out.println("\nNode sequence from preorder traversal = " + list);
/* Inorder traversal */
list.clear();
inOrder(root);
System.out.println("\nInorder traversal node print sequence = " + list);
System.out.println("\nNode sequence from inorder traversal = " + list);
/* Postorder traversal */
list.clear();
postOrder(root);
System.out.println("\nPostorder traversal node print sequence = " + list);
System.out.println("\nNode sequence from postorder traversal = " + list);
}
}

View File

@@ -15,7 +15,7 @@ public class ListNode {
val = x;
}
/* Deserialize a list into a linked list */
/* Deserialize an array into a linked list */
public static ListNode arrToLinkedList(int[] arr) {
ListNode dum = new ListNode(0);
ListNode head = dum;

View File

@@ -19,7 +19,7 @@ class Trunk {
};
public class PrintUtil {
/* Print matrix (Array) */
/* Print a matrix (array) */
public static <T> void printMatrix(T[][] matrix) {
System.out.println("[");
for (T[] row : matrix) {
@@ -28,7 +28,7 @@ public class PrintUtil {
System.out.println("]");
}
/* Print matrix (List) */
/* Print a matrix (list) */
public static <T> void printMatrix(List<List<T>> matrix) {
System.out.println("[");
for (List<T> row : matrix) {
@@ -37,7 +37,7 @@ public class PrintUtil {
System.out.println("]");
}
/* Print linked list */
/* Print a linked list */
public static void printLinkedList(ListNode head) {
List<String> list = new ArrayList<>();
while (head != null) {
@@ -47,13 +47,13 @@ public class PrintUtil {
System.out.println(String.join(" -> ", list));
}
/* Print binary tree */
/* Print a binary tree */
public static void printTree(TreeNode root) {
printTree(root, null, false);
}
/**
* 打印二叉树
* Print a binary tree
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
@@ -97,19 +97,19 @@ public class PrintUtil {
System.out.print(p.str);
}
/* Print hash table */
/* Print the hash table */
public static <K, V> void printHashMap(Map<K, V> map) {
for (Map.Entry<K, V> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
}
/* Print heap (priority queue) */
/* Print a heap (priority queue) */
public static void printHeap(Queue<Integer> queue) {
List<Integer> list = new ArrayList<>(queue);
System.out.print("Heap array representation:");
System.out.print("Array representation of the heap:");
System.out.println(list);
System.out.println("Heap tree representation:");
System.out.println("Tree representation of the heap:");
TreeNode root = TreeNode.listToTree(list);
printTree(root);
}

View File

@@ -12,19 +12,19 @@ import java.util.*;
public class TreeNode {
public int val; // Node value
public int height; // Node height
public TreeNode left; // Reference to left child node
public TreeNode right; // Reference to right child node
public TreeNode left; // Reference to the left child
public TreeNode right; // Reference to the right child
/* Constructor */
public TreeNode(int x) {
val = x;
}
// For the serialization encoding rules, please refer to:
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
// Array representation of binary tree:
// For the serialization rules, see:
// https://www.hello-algo.com/en/chapter_tree/array_representation_of_tree/
// Array representation of the binary tree:
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
// Linked list representation of binary tree:
// Linked representation of the binary tree:
// /——— 15
// /——— 7
// /——— 3

View File

@@ -16,7 +16,7 @@ public class Vertex {
this.val = val;
}
/* Input value list vals, return vertex list vets */
/* Given the array of values vals, return the array of vertices vets */
public static Vertex[] valsToVets(int[] vals) {
Vertex[] vets = new Vertex[vals.length];
for (int i = 0; i < vals.length; i++) {
@@ -25,7 +25,7 @@ public class Vertex {
return vets;
}
/* Input vertex list vets, return value list vals */
/* Given the list of vertices vets, return the list of values vals */
public static List<Integer> vetsToVals(List<Vertex> vets) {
List<Integer> vals = new ArrayList<>();
for (Vertex vet : vets) {