mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-25 21:23:21 +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:
@@ -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}")
|
||||
|
||||
Reference in New Issue
Block a user