translation: Add Python and Java code for EN version (#1345)

* Add the intial translation of code of all the languages

* test

* revert

* Remove

* Add Python and Java code for EN version
This commit is contained in:
Yudong Jin
2024-05-06 05:21:51 +08:00
committed by GitHub
parent b5e198db7d
commit 1c0f350ad6
174 changed files with 12349 additions and 0 deletions

View File

@ -0,0 +1,52 @@
"""
File: binary_search.py
Created Time: 2022-11-26
Author: timi (xisunyy@163.com)
"""
def binary_search(nums: list[int], target: int) -> int:
"""Binary search (double closed interval)"""
# Initialize double closed interval [0, n-1], i.e., i, j point to the first element and last element of the array respectively
i, j = 0, len(nums) - 1
# Loop until the search interval is empty (when i > j, it is empty)
while i <= j:
# Theoretically, Python's numbers can be infinitely large (depending on memory size), so there is no need to consider large number overflow
m = (i + j) // 2 # Calculate midpoint index m
if nums[m] < target:
i = m + 1 # This situation indicates that target is in the interval [m+1, j]
elif nums[m] > target:
j = m - 1 # This situation indicates that target is in the interval [i, m-1]
else:
return m # Found the target element, thus return its index
return -1 # Did not find the target element, thus 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 the last element +1 of the array respectively
i, j = 0, len(nums)
# Loop until the search interval is empty (when i = j, it is empty)
while i < j:
m = (i + j) // 2 # Calculate midpoint index m
if nums[m] < target:
i = m + 1 # This situation indicates that target is in the interval [m+1, j)
elif nums[m] > target:
j = m # This situation indicates that target is in the interval [i, m)
else:
return m # Found the target element, thus return its index
return -1 # Did not find the target element, thus return -1
"""Driver Code"""
if __name__ == "__main__":
target = 6
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
# Binary search (double closed interval)
index = binary_search(nums, target)
print("Index of target element 6 =", index)
# Binary search (left closed right open interval)
index = binary_search_lcro(nums, target)
print("Index of target element 6 =", index)

View File

@ -0,0 +1,49 @@
"""
File: binary_search_edge.py
Created Time: 2023-08-04
Author: krahets (krahets@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
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
i = binary_search_insertion(nums, target)
# Did not find target, thus return -1
if i == len(nums) or nums[i] != target:
return -1
# Found target, 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
i = binary_search_insertion(nums, target + 1)
# j points to the rightmost target, i points to the first element greater than target
j = i - 1
# Did not find target, thus return -1
if j == -1 or nums[j] != target:
return -1
# Found target, return index j
return j
"""Driver Code"""
if __name__ == "__main__":
# Array with duplicate elements
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
print(f"\nArray nums = {nums}")
# Binary search for left and right boundaries
for target in [6, 7]:
index = binary_search_left_edge(nums, target)
print(f"The index of the leftmost element {target} is {index}")
index = binary_search_right_edge(nums, target)
print(f"The index of the rightmost element {target} is {index}")

View File

@ -0,0 +1,54 @@
"""
File: binary_search_insertion.py
Created Time: 2023-08-04
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 double closed interval [0, n-1]
while i <= j:
m = (i + j) // 2 # Calculate midpoint index m
if nums[m] < target:
i = m + 1 # Target is in interval [m+1, j]
elif nums[m] > target:
j = m - 1 # Target is in interval [i, m-1]
else:
return m # Found target, return insertion point m
# Did not find target, 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 double closed interval [0, n-1]
while i <= j:
m = (i + j) // 2 # Calculate midpoint index m
if nums[m] < target:
i = m + 1 # Target is in interval [m+1, j]
elif nums[m] > target:
j = m - 1 # Target is in interval [i, m-1]
else:
j = m - 1 # First element less than target is in interval [i, m-1]
# Return insertion point i
return i
"""Driver Code"""
if __name__ == "__main__":
# Array without duplicate elements
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
print(f"\nArray nums = {nums}")
# Binary search for insertion point
for target in [6, 9]:
index = binary_search_insertion_simple(nums, target)
print(f"Element {target}'s insertion point index is {index}")
# Array with duplicate elements
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
print(f"\nArray nums = {nums}")
# Binary search for insertion point
for target in [2, 6, 20]:
index = binary_search_insertion(nums, target)
print(f"Element {target}'s insertion point index is {index}")

View File

@ -0,0 +1,51 @@
"""
File: hashing_search.py
Created Time: 2022-11-26
Author: timi (xisunyy@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
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 the hash table does not contain this key, return -1
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 the hash table does not contain this key, return None
return hmap.get(target, None)
"""Driver Code"""
if __name__ == "__main__":
target = 3
# Hash search (array)
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
# Initialize hash table
map0 = dict[int, int]()
for i in range(len(nums)):
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)
head: ListNode = list_to_linked_list(nums)
# Initialize hash table
map1 = dict[int, ListNode]()
while head:
map1[head.val] = head # key: node value, value: node
head = head.next
node: ListNode = hashing_search_linkedlist(map1, target)
print("Target node value 3's corresponding node object is", node)

View File

@ -0,0 +1,45 @@
"""
File: linear_search.py
Created Time: 2022-11-26
Author: timi (xisunyy@163.com)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import ListNode, list_to_linked_list
def linear_search_array(nums: list[int], target: int) -> int:
"""Linear search (array)"""
# Traverse array
for i in range(len(nums)):
if nums[i] == target: # Found the target element, thus return its index
return i
return -1 # Did not find the target element, thus return -1
def linear_search_linkedlist(head: ListNode, target: int) -> ListNode | None:
"""Linear search (linked list)"""
# Traverse the list
while head:
if head.val == target: # Found the target node, return it
return head
head = head.next
return None # Did not find the target node, thus return None
"""Driver Code"""
if __name__ == "__main__":
target = 3
# Perform linear search in 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
head: ListNode = list_to_linked_list(nums)
node: ListNode | None = linear_search_linkedlist(head, target)
print("Target node value 3's corresponding node object is", node)

View File

@ -0,0 +1,42 @@
"""
File: two_sum.py
Created Time: 2022-11-25
Author: krahets (krahets@163.com)
"""
def two_sum_brute_force(nums: list[int], target: int) -> list[int]:
"""Method one: Brute force enumeration"""
# Two-layer loop, time complexity is O(n^2)
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
"""Method two: Auxiliary hash table"""
# Auxiliary hash table, space complexity is O(n)
dic = {}
# Single-layer loop, time complexity is O(n)
for i in range(len(nums)):
if target - nums[i] in dic:
return [dic[target - nums[i]], i]
dic[nums[i]] = i
return []
"""Driver Code"""
if __name__ == "__main__":
# ======= Test Case =======
nums = [2, 7, 11, 15]
target = 13
# ====== Driver Code ======
# Method one
res: list[int] = two_sum_brute_force(nums, target)
print("Method one res =", res)
# Method two
res: list[int] = two_sum_hash_table(nums, target)
print("Method two res =", res)