mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-23 04:02:44 +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:
@@ -7,46 +7,46 @@ Author: timi (xisunyy@163.com)
|
||||
|
||||
def binary_search(nums: list[int], target: int) -> int:
|
||||
"""Binary search (closed interval)"""
|
||||
# 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
|
||||
i, j = 0, len(nums) - 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:
|
||||
# In theory, Python numbers can be infinitely large (depending on memory size), no need to consider large number overflow
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
# Python integers can grow arbitrarily large, subject to available memory, so integer overflow is not a concern
|
||||
m = (i + j) // 2 # Calculate the midpoint index m
|
||||
if nums[m] < target:
|
||||
i = m + 1 # This means target is in the interval [m+1, j]
|
||||
i = m + 1 # In this case, target must be in [m+1, j] if it exists
|
||||
elif nums[m] > target:
|
||||
j = m - 1 # This means target is in the interval [i, m-1]
|
||||
j = m - 1 # In this case, target must be in [i, m-1] if it exists
|
||||
else:
|
||||
return m # Found the target element, return its index
|
||||
return -1 # Target element not found, return -1
|
||||
return m # The target element was found; return its index
|
||||
return -1 # The target element was not found; return -1
|
||||
|
||||
|
||||
def binary_search_lcro(nums: list[int], target: int) -> int:
|
||||
"""Binary search (left-closed right-open interval)"""
|
||||
# Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
|
||||
"""Binary search (left-closed, right-open interval)"""
|
||||
# Initialize the left-closed, right-open interval [0, n), with i at the first element and j one past the last
|
||||
i, j = 0, len(nums)
|
||||
# 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:
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = (i + j) // 2 # Calculate the midpoint index m
|
||||
if nums[m] < target:
|
||||
i = m + 1 # This means target is in the interval [m+1, j)
|
||||
i = m + 1 # In this case, target must be in [m+1, j) if it exists
|
||||
elif nums[m] > target:
|
||||
j = m # This means target is in the interval [i, m)
|
||||
j = m # In this case, target must be in [i, m) if it exists
|
||||
else:
|
||||
return m # Found the target element, return its index
|
||||
return -1 # Target element not found, return -1
|
||||
return m # The target element was found; return its index
|
||||
return -1 # The target element was not found; return -1
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
target = 6
|
||||
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
|
||||
# Binary search (closed interval)
|
||||
index = binary_search(nums, target)
|
||||
print("Index of target element 6 =", index)
|
||||
print("Index of target element 6 = ", index)
|
||||
|
||||
# Binary search (left-closed right-open interval)
|
||||
# Binary search (left-closed, right-open interval)
|
||||
index = binary_search_lcro(nums, target)
|
||||
print("Index of target element 6 =", index)
|
||||
print("Index of target element 6 = ", index)
|
||||
|
||||
@@ -12,38 +12,38 @@ from binary_search_insertion import binary_search_insertion
|
||||
|
||||
|
||||
def binary_search_left_edge(nums: list[int], target: int) -> int:
|
||||
"""Binary search for the leftmost target"""
|
||||
# Equivalent to finding the insertion point of target
|
||||
"""Find the leftmost occurrence of target using binary search"""
|
||||
# This is equivalent to finding the insertion point of target
|
||||
i = binary_search_insertion(nums, target)
|
||||
# Target not found, return -1
|
||||
# If target was not found, return -1
|
||||
if i == len(nums) or nums[i] != target:
|
||||
return -1
|
||||
# Found target, return index i
|
||||
# Target was found; return index i
|
||||
return i
|
||||
|
||||
|
||||
def binary_search_right_edge(nums: list[int], target: int) -> int:
|
||||
"""Binary search for the rightmost target"""
|
||||
# Convert to finding the leftmost target + 1
|
||||
"""Find the rightmost occurrence of target using binary search"""
|
||||
# Reduce the problem to finding the leftmost insertion point of target + 1
|
||||
i = binary_search_insertion(nums, target + 1)
|
||||
# j points to the rightmost target, i points to the first element greater than target
|
||||
# j is the candidate rightmost target index; i is the index of the first element greater than target, or len(nums)
|
||||
j = i - 1
|
||||
# Target not found, return -1
|
||||
# If target was not found, return -1
|
||||
if j == -1 or nums[j] != target:
|
||||
return -1
|
||||
# Found target, return index j
|
||||
# Target was found; return index j
|
||||
return j
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Array with duplicate elements
|
||||
# Array containing duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print(f"\nArray nums = {nums}")
|
||||
|
||||
# Binary search for left boundary and right boundary
|
||||
# Find the left and right boundaries using binary search
|
||||
for target in [6, 7]:
|
||||
index = binary_search_left_edge(nums, target)
|
||||
print(f"Index of the leftmost element {target} is {index}")
|
||||
print(f"Index of the leftmost occurrence of {target}: {index}")
|
||||
index = binary_search_right_edge(nums, target)
|
||||
print(f"Index of the rightmost element {target} is {index}")
|
||||
print(f"Index of the rightmost occurrence of {target}: {index}")
|
||||
|
||||
@@ -6,49 +6,49 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def binary_search_insertion_simple(nums: list[int], target: int) -> int:
|
||||
"""Binary search for insertion point (no duplicate elements)"""
|
||||
i, j = 0, len(nums) - 1 # Initialize closed interval [0, n-1]
|
||||
"""Find an insertion point using binary search (no duplicates)"""
|
||||
i, j = 0, len(nums) - 1 # Initialize the closed interval [0, n-1]
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = (i + j) // 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
|
||||
elif 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
|
||||
# Target not found, return insertion point i
|
||||
return m # Target was found; return insertion point m
|
||||
# Target was not found; return insertion point i
|
||||
return i
|
||||
|
||||
|
||||
def binary_search_insertion(nums: list[int], target: int) -> int:
|
||||
"""Binary search for insertion point (with duplicate elements)"""
|
||||
i, j = 0, len(nums) - 1 # Initialize closed interval [0, n-1]
|
||||
"""Find an insertion point using binary search (with duplicates)"""
|
||||
i, j = 0, len(nums) - 1 # Initialize the closed interval [0, n-1]
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # Calculate midpoint index m
|
||||
m = (i + j) // 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
|
||||
elif nums[m] > target:
|
||||
j = m - 1 # target is in the interval [i, m-1]
|
||||
j = m - 1 # Target must be in [i, m-1] if it exists
|
||||
else:
|
||||
j = m - 1 # The rightmost element less than target is in the interval [i, m-1]
|
||||
j = m - 1 # Continue in [i, m-1] to find the rightmost element smaller than target
|
||||
# Return insertion point i
|
||||
return i
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Array without duplicate elements
|
||||
# Array with no duplicate elements
|
||||
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
print(f"\nArray nums = {nums}")
|
||||
# Binary search for insertion point
|
||||
# Find an insertion point using binary search
|
||||
for target in [6, 9]:
|
||||
index = binary_search_insertion_simple(nums, target)
|
||||
print(f"Index of insertion point for element {target} is {index}")
|
||||
print(f"Insertion index for element {target}: {index}")
|
||||
|
||||
# Array with duplicate elements
|
||||
# Array containing duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print(f"\nArray nums = {nums}")
|
||||
# Binary search for insertion point
|
||||
# Find an insertion point using binary search
|
||||
for target in [2, 6, 20]:
|
||||
index = binary_search_insertion(nums, target)
|
||||
print(f"Index of insertion point for element {target} is {index}")
|
||||
print(f"Insertion index for element {target}: {index}")
|
||||
|
||||
@@ -12,40 +12,40 @@ from modules import ListNode, list_to_linked_list
|
||||
|
||||
|
||||
def hashing_search_array(hmap: dict[int, int], target: int) -> int:
|
||||
"""Hash search (array)"""
|
||||
# Hash table's key: target element, value: index
|
||||
# If this key does not exist in the hash table, return -1
|
||||
"""Hash-based search (array)"""
|
||||
# Hash table key: target element; value: index
|
||||
# Return -1 if the hash table does not contain this key
|
||||
return hmap.get(target, -1)
|
||||
|
||||
|
||||
def hashing_search_linkedlist(
|
||||
hmap: dict[int, ListNode], target: int
|
||||
) -> ListNode | None:
|
||||
"""Hash search (linked list)"""
|
||||
# Hash table's key: target element, value: node object
|
||||
# If this key does not exist in the hash table, return None
|
||||
"""Hash-based search (linked list)"""
|
||||
# Hash table key: target element; value: node object
|
||||
# Return None if the hash table does not contain this key
|
||||
return hmap.get(target, None)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
target = 3
|
||||
|
||||
# Hash search (array)
|
||||
# Hash-based search (array)
|
||||
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
# Initialize hash table
|
||||
# Initialize the hash table
|
||||
map0 = dict[int, int]()
|
||||
for i in range(len(nums)):
|
||||
map0[nums[i]] = i # key: element, value: index
|
||||
map0[nums[i]] = i # key: element; value: index
|
||||
index: int = hashing_search_array(map0, target)
|
||||
print("Index of target element 3 =", index)
|
||||
|
||||
# Hash search (linked list)
|
||||
# Hash-based search (linked list)
|
||||
head: ListNode = list_to_linked_list(nums)
|
||||
# Initialize hash table
|
||||
# Initialize the hash table
|
||||
map1 = dict[int, ListNode]()
|
||||
while head:
|
||||
map1[head.val] = head # key: node value, value: node
|
||||
map1[head.val] = head # key: node value; value: node
|
||||
head = head.next
|
||||
node: ListNode = hashing_search_linkedlist(map1, target)
|
||||
print("The corresponding node object for target node value 3 is", node)
|
||||
print("The node object corresponding to target value 3 is", node)
|
||||
|
||||
@@ -15,31 +15,31 @@ def linear_search_array(nums: list[int], target: int) -> int:
|
||||
"""Linear search (array)"""
|
||||
# Traverse the array
|
||||
for i in range(len(nums)):
|
||||
if nums[i] == target: # Found the target element, return its index
|
||||
if nums[i] == target: # The target element was found; return its index
|
||||
return i
|
||||
return -1 # Target element not found, return -1
|
||||
return -1 # The target element was not found; return -1
|
||||
|
||||
|
||||
def linear_search_linkedlist(head: ListNode, target: int) -> ListNode | None:
|
||||
"""Linear search (linked list)"""
|
||||
# Traverse the linked list
|
||||
while head:
|
||||
if head.val == target: # Found the target node, return it
|
||||
if head.val == target: # The target node was found; return it
|
||||
return head
|
||||
head = head.next
|
||||
return None # Target node not found, return None
|
||||
return None # The target node was not found; return None
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
target = 3
|
||||
|
||||
# Perform linear search in array
|
||||
# Perform linear search on the array
|
||||
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
index: int = linear_search_array(nums, target)
|
||||
print("Index of target element 3 =", index)
|
||||
|
||||
# Perform linear search in linked list
|
||||
# Perform linear search on the linked list
|
||||
head: ListNode = list_to_linked_list(nums)
|
||||
node: ListNode | None = linear_search_linkedlist(head, target)
|
||||
print("The corresponding node object for target node value 3 is", node)
|
||||
print("The node object corresponding to target value 3 is", node)
|
||||
|
||||
@@ -6,8 +6,8 @@ Author: krahets (krahets@163.com)
|
||||
|
||||
|
||||
def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
|
||||
"""Method 1: Brute force enumeration"""
|
||||
# Two nested loops, time complexity is O(n^2)
|
||||
"""Method 1: brute-force enumeration"""
|
||||
# Two nested loops give a time complexity of O(n^2)
|
||||
for i in range(len(nums) - 1):
|
||||
for j in range(i + 1, len(nums)):
|
||||
if nums[i] + nums[j] == target:
|
||||
@@ -16,10 +16,10 @@ def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
|
||||
|
||||
|
||||
def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
|
||||
"""Method 2: Auxiliary hash table"""
|
||||
# Auxiliary hash table, space complexity is O(n)
|
||||
"""Method 2: auxiliary hash table"""
|
||||
# The auxiliary hash table uses O(n) space
|
||||
dic = {}
|
||||
# Single loop, time complexity is O(n)
|
||||
# A single loop with average O(1) hash operations gives an average time complexity of O(n)
|
||||
for i in range(len(nums)):
|
||||
if target - nums[i] in dic:
|
||||
return [dic[target - nums[i]], i]
|
||||
@@ -27,16 +27,16 @@ def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
|
||||
return []
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# ======= Test Case =======
|
||||
# ======= Test case =======
|
||||
nums = [2, 7, 11, 15]
|
||||
target = 13
|
||||
|
||||
# ====== Driver Code ======
|
||||
# ====== Driver code ======
|
||||
# Method 1
|
||||
res: list[int] = two_sum_brute_force(nums, target)
|
||||
print("Method 1 res =", res)
|
||||
print("Method 1: res =", res)
|
||||
# Method 2
|
||||
res: list[int] = two_sum_hash_table(nums, target)
|
||||
print("Method 2 res =", res)
|
||||
print("Method 2: res =", res)
|
||||
|
||||
Reference in New Issue
Block a user