mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-11 08:20:38 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
* Author: Hello Algo Team
|
||||
*/
|
||||
|
||||
/* Iterative summation */
|
||||
/* Sum using iteration */
|
||||
function sumIter(n) {
|
||||
let res = 0;
|
||||
for (let i = 1; i <= n; i++) {
|
||||
@@ -13,7 +13,7 @@ function sumIter(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Recursive summation */
|
||||
/* Sum using recursion */
|
||||
function sumRecur(n) {
|
||||
if (n === 1) {
|
||||
return 1;
|
||||
@@ -21,7 +21,7 @@ function sumRecur(n) {
|
||||
return n + sumRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Linear loop */
|
||||
/* Linear-time loop */
|
||||
function linearLoop(n) {
|
||||
let res = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -30,7 +30,7 @@ function linearLoop(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Quadratic loop */
|
||||
/* Quadratic-time loop */
|
||||
function quadraticLoop(n) {
|
||||
let res = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -41,7 +41,7 @@ function quadraticLoop(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Logarithmic loop */
|
||||
/* Logarithmic-time loop */
|
||||
function logarithmicLoop(n) {
|
||||
while (n > 1) {
|
||||
n = Math.floor(n / 2);
|
||||
@@ -59,5 +59,5 @@ if (
|
||||
logarithmicLoop(4) !== 1 ||
|
||||
logarithmicLoop(5) !== 1
|
||||
) {
|
||||
throw new Error('complexity exercise check failed');
|
||||
throw new Error('Complexity exercise check failed');
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/* for loop */
|
||||
function forLoop(n) {
|
||||
let res = 0;
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
for (let i = 1; i <= n; i++) {
|
||||
res += i;
|
||||
}
|
||||
@@ -17,11 +17,11 @@ function forLoop(n) {
|
||||
/* while loop */
|
||||
function whileLoop(n) {
|
||||
let res = 0;
|
||||
let i = 1; // Initialize condition variable
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
let i = 1; // Initialize the loop control variable
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
i++; // Update condition variable
|
||||
i++; // Update the loop control variable
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -29,23 +29,23 @@ function whileLoop(n) {
|
||||
/* while loop (two updates) */
|
||||
function whileLoopII(n) {
|
||||
let res = 0;
|
||||
let i = 1; // Initialize condition variable
|
||||
// Sum 1, 4, 10, ...
|
||||
let i = 1; // Initialize the loop control variable
|
||||
// Sum 1, 4, 10, ... in a loop
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
// Update condition variable
|
||||
// Update the loop control variable
|
||||
i++;
|
||||
i *= 2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
/* Nested for loops */
|
||||
function nestedForLoop(n) {
|
||||
let res = '';
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
// Loop over i = 1, 2, ..., n-1, n
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
// Loop over j = 1, 2, ..., n-1, n
|
||||
for (let j = 1; j <= n; j++) {
|
||||
res += `(${i}, ${j}), `;
|
||||
}
|
||||
@@ -53,18 +53,18 @@ function nestedForLoop(n) {
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 5;
|
||||
let res;
|
||||
|
||||
res = forLoop(n);
|
||||
console.log(`For loop sum result res = ${res}`);
|
||||
console.log(`Sum from the for loop: res = ${res}`);
|
||||
|
||||
res = whileLoop(n);
|
||||
console.log(`While loop sum result res = ${res}`);
|
||||
console.log(`Sum from the while loop: res = ${res}`);
|
||||
|
||||
res = whileLoopII(n);
|
||||
console.log(`While loop (two updates) sum result res = ${res}`);
|
||||
console.log(`Sum from the while loop with two updates: res = ${res}`);
|
||||
|
||||
const resStr = nestedForLoop(n);
|
||||
console.log(`Nested for loop traversal result ${resStr}`);
|
||||
console.log(`Traversal result from the nested for loops: ${resStr}`);
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
/* Recursion */
|
||||
function recur(n) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (n === 1) return 1;
|
||||
// Recurse: recursive call
|
||||
// Recurse: make a recursive call
|
||||
const res = recur(n - 1);
|
||||
// Return: return result
|
||||
// Unwind: return the result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
@@ -19,14 +19,14 @@ function forLoopRecur(n) {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
const stack = [];
|
||||
let res = 0;
|
||||
// Recurse: recursive call
|
||||
// Recurse: make a recursive call
|
||||
for (let i = n; i > 0; i--) {
|
||||
// Simulate "recurse" with "push"
|
||||
// Simulate recursive calls by pushing onto the stack
|
||||
stack.push(i);
|
||||
}
|
||||
// Return: return result
|
||||
// Unwind: return the result
|
||||
while (stack.length) {
|
||||
// Simulate "return" with "pop"
|
||||
// Simulate unwinding by popping from the stack
|
||||
res += stack.pop();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
@@ -35,35 +35,35 @@ function forLoopRecur(n) {
|
||||
|
||||
/* Tail recursion */
|
||||
function tailRecur(n, res) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (n === 0) return res;
|
||||
// Tail recursive call
|
||||
// Tail-recursive call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
function fib(n) {
|
||||
// Termination condition f(1) = 0, f(2) = 1
|
||||
// Base cases: f(1) = 0, f(2) = 1
|
||||
if (n === 1 || n === 2) return n - 1;
|
||||
// Recursive call f(n) = f(n-1) + f(n-2)
|
||||
// Recursive calls: f(n) = f(n-1) + f(n-2)
|
||||
const res = fib(n - 1) + fib(n - 2);
|
||||
// Return result f(n)
|
||||
// Return the result f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 5;
|
||||
let res;
|
||||
|
||||
res = recur(n);
|
||||
console.log(`Recursion sum result res = ${res}`);
|
||||
console.log(`Sum from the recursive function: res = ${res}`);
|
||||
|
||||
res = forLoopRecur(n);
|
||||
console.log(`Using iteration to simulate recursion sum result res = ${res}`);
|
||||
console.log(`Sum from simulating recursion with iteration: res = ${res}`);
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
console.log(`Tail recursion sum result res = ${res}`);
|
||||
console.log(`Sum from the tail-recursive function: res = ${res}`);
|
||||
|
||||
res = fib(n);
|
||||
console.log(`The ${n}th Fibonacci number is ${res}`);
|
||||
console.log(`Fibonacci term ${n} is ${res}`);
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ function constFunc() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
/* Constant complexity */
|
||||
function constant(n) {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
// Constants, variables, and objects occupy O(1) space
|
||||
const a = 0;
|
||||
const b = 0;
|
||||
const nums = new Array(10000);
|
||||
@@ -25,42 +25,42 @@ function constant(n) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = 0;
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
// Function calls in the loop occupy O(1) space
|
||||
for (let i = 0; i < n; i++) {
|
||||
constFunc();
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
/* Linear complexity */
|
||||
function linear(n) {
|
||||
// Array of length n uses O(n) space
|
||||
// An array of length n uses O(n) space
|
||||
const nums = new Array(n);
|
||||
// A list of length n occupies O(n) space
|
||||
const nodes = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
nodes.push(new ListNode(i));
|
||||
}
|
||||
// A hash table of length n occupies O(n) space
|
||||
// A hash table with n entries occupies O(n) space
|
||||
const map = new Map();
|
||||
for (let i = 0; i < n; i++) {
|
||||
map.set(i, i.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
/* Linear complexity (recursive implementation) */
|
||||
function linearRecur(n) {
|
||||
console.log(`Recursion n = ${n}`);
|
||||
console.log(`Recursive call with n = ${n}`);
|
||||
if (n === 1) return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
/* Quadratic complexity */
|
||||
function quadratic(n) {
|
||||
// Matrix uses O(n^2) space
|
||||
// The matrix uses O(n^2) space
|
||||
const numMatrix = Array(n)
|
||||
.fill(null)
|
||||
.map(() => Array(n).fill(null));
|
||||
// 2D list uses O(n^2) space
|
||||
// The two-dimensional list occupies O(n^2) space
|
||||
const numList = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const tmp = [];
|
||||
@@ -71,15 +71,15 @@ function quadratic(n) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Quadratic order (recursive implementation) */
|
||||
/* Quadratic complexity (recursive implementation) */
|
||||
function quadraticRecur(n) {
|
||||
if (n <= 0) return 0;
|
||||
const nums = new Array(n);
|
||||
console.log(`In recursion n = ${n}, nums length = ${nums.length}`);
|
||||
console.log(`In the recursive call with n = ${n}, nums has length ${nums.length}`);
|
||||
return quadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Exponential complexity (building a perfect binary tree) */
|
||||
function buildTree(n) {
|
||||
if (n === 0) return null;
|
||||
const root = new TreeNode(0);
|
||||
@@ -88,16 +88,16 @@ function buildTree(n) {
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const n = 5;
|
||||
// Constant order
|
||||
// Constant complexity
|
||||
constant(n);
|
||||
// Linear order
|
||||
// Linear complexity
|
||||
linear(n);
|
||||
linearRecur(n);
|
||||
// Exponential order
|
||||
// Quadratic complexity
|
||||
quadratic(n);
|
||||
quadraticRecur(n);
|
||||
// Exponential order
|
||||
// Exponential complexity
|
||||
const root = buildTree(n);
|
||||
printTree(root);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Author: RiverTwilight (contact@rene.wang)
|
||||
*/
|
||||
|
||||
/* Constant order */
|
||||
/* Constant complexity */
|
||||
function constant(n) {
|
||||
let count = 0;
|
||||
const size = 100000;
|
||||
@@ -12,27 +12,27 @@ function constant(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
/* Linear complexity */
|
||||
function linear(n) {
|
||||
let count = 0;
|
||||
for (let i = 0; i < n; i++) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order (traversing array) */
|
||||
/* Linear complexity (array traversal) */
|
||||
function arrayTraversal(nums) {
|
||||
let count = 0;
|
||||
// Number of iterations is proportional to the array length
|
||||
// The number of iterations is proportional to the array length
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
/* Quadratic complexity */
|
||||
function quadratic(n) {
|
||||
let count = 0;
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
// The number of iterations is proportional to the square of the input size n
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
count++;
|
||||
@@ -41,30 +41,30 @@ function quadratic(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Quadratic order (bubble sort) */
|
||||
/* Quadratic complexity (bubble sort) */
|
||||
function bubbleSort(nums) {
|
||||
let count = 0; // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
count += 3; // Element swap includes 3 unit operations
|
||||
count += 3; // Swapping two elements takes 3 elementary operations
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (loop implementation) */
|
||||
/* Exponential complexity (iterative implementation) */
|
||||
function exponential(n) {
|
||||
let count = 0,
|
||||
base = 1;
|
||||
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
// Each cell divides into two per round, giving the sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < base; j++) {
|
||||
count++;
|
||||
@@ -75,13 +75,13 @@ function exponential(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (recursive implementation) */
|
||||
/* Exponential complexity (recursive implementation) */
|
||||
function expRecur(n) {
|
||||
if (n === 1) return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
/* Logarithmic complexity (iterative implementation) */
|
||||
function logarithmic(n) {
|
||||
let count = 0;
|
||||
while (n > 1) {
|
||||
@@ -91,13 +91,13 @@ function logarithmic(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
/* Logarithmic complexity (recursive implementation) */
|
||||
function logRecur(n) {
|
||||
if (n <= 1) return 0;
|
||||
return logRecur(n / 2) + 1;
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
/* Linearithmic complexity */
|
||||
function linearLogRecur(n) {
|
||||
if (n <= 1) return 1;
|
||||
let count = linearLogRecur(n / 2) + linearLogRecur(n / 2);
|
||||
@@ -107,49 +107,49 @@ function linearLogRecur(n) {
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
/* Factorial complexity (recursive implementation) */
|
||||
function factorialRecur(n) {
|
||||
if (n === 0) return 1;
|
||||
let count = 0;
|
||||
// Split from 1 into n
|
||||
// Split one problem into n subproblems
|
||||
for (let i = 0; i < n; i++) {
|
||||
count += factorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
/* Driver code */
|
||||
// Try different values of n to see how the operation count grows for each complexity
|
||||
const n = 8;
|
||||
console.log('Input data size n = ' + n);
|
||||
console.log('Input size n = ' + n);
|
||||
|
||||
let count = constant(n);
|
||||
console.log('Constant order operation count = ' + count);
|
||||
console.log('Operation count for constant complexity = ' + count);
|
||||
|
||||
count = linear(n);
|
||||
console.log('Linear order operation count = ' + count);
|
||||
console.log('Operation count for linear complexity = ' + count);
|
||||
count = arrayTraversal(new Array(n));
|
||||
console.log('Linear order (array traversal) operation count = ' + count);
|
||||
console.log('Operation count for linear complexity (array traversal) = ' + count);
|
||||
|
||||
count = quadratic(n);
|
||||
console.log('Quadratic order operation count = ' + count);
|
||||
console.log('Operation count for quadratic complexity = ' + count);
|
||||
let nums = new Array(n);
|
||||
for (let i = 0; i < n; i++) nums[i] = n - i; // [n,n-1,...,2,1]
|
||||
count = bubbleSort(nums);
|
||||
console.log('Quadratic order (bubble sort) operation count = ' + count);
|
||||
console.log('Operation count for quadratic complexity (bubble sort) = ' + count);
|
||||
|
||||
count = exponential(n);
|
||||
console.log('Exponential order (loop implementation) operation count = ' + count);
|
||||
console.log('Operation count for exponential complexity (iterative implementation) = ' + count);
|
||||
count = expRecur(n);
|
||||
console.log('Exponential order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for exponential complexity (recursive implementation) = ' + count);
|
||||
|
||||
count = logarithmic(n);
|
||||
console.log('Logarithmic order (loop implementation) operation count = ' + count);
|
||||
console.log('Operation count for logarithmic complexity (iterative implementation) = ' + count);
|
||||
count = logRecur(n);
|
||||
console.log('Logarithmic order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for logarithmic complexity (recursive implementation) = ' + count);
|
||||
|
||||
count = linearLogRecur(n);
|
||||
console.log('Linearithmic order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for linearithmic complexity (recursive implementation) = ' + count);
|
||||
|
||||
count = factorialRecur(n);
|
||||
console.log('Factorial order (recursive implementation) operation count = ' + count);
|
||||
console.log('Operation count for factorial complexity (recursive implementation) = ' + count);
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
* Author: RiverTwilight (contact@rene.wang)
|
||||
*/
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
/* Generate an array containing { 1, 2, ..., n } in shuffled order */
|
||||
function randomNumbers(n) {
|
||||
const nums = Array(n);
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
// Generate the array nums = { 1, 2, 3, ..., n }
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
// Randomly shuffle array elements
|
||||
// Randomly shuffle the array elements
|
||||
for (let i = 0; i < n; i++) {
|
||||
const r = Math.floor(Math.random() * (i + 1));
|
||||
const temp = nums[i];
|
||||
@@ -21,11 +21,11 @@ function randomNumbers(n) {
|
||||
return nums;
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
/* Find the index of the number 1 in array nums */
|
||||
function findOne(nums) {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
// When element 1 is at the head of the array, best time complexity O(1) is achieved
|
||||
// When element 1 is at the tail of the array, worst time complexity O(n) is achieved
|
||||
// When 1 is at the start of the array, the best-case time complexity is O(1)
|
||||
// When 1 is at the end of the array, the worst-case time complexity is O(n)
|
||||
if (nums[i] === 1) {
|
||||
return i;
|
||||
}
|
||||
@@ -33,11 +33,11 @@ function findOne(nums) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const n = 100;
|
||||
const nums = randomNumbers(n);
|
||||
const index = findOne(nums);
|
||||
console.log('\nArray [ 1, 2, ..., n ] after shuffling = [' + nums.join(', ') + ']');
|
||||
console.log('Index of number 1 is ' + index);
|
||||
console.log('The index of the number 1 is ' + index);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user