mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-28 23:34:43 +08:00
feat(ko): add the Korean online edition (#2006)
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
This commit is contained in:
52
ko/codes/python/chapter_searching/binary_search.py
Normal file
52
ko/codes/python/chapter_searching/binary_search.py
Normal 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:
|
||||
"""이진 탐색(양 끝을 포함하는 닫힌 구간)"""
|
||||
# 닫힌 구간 [0, n-1]을 초기화한다. i와 j는 각각 배열의 첫 원소와 마지막 원소를 가리킨다
|
||||
i, j = 0, len(nums) - 1
|
||||
# 반복하다 탐색 구간이 비면 종료한다(i > j이면 빈 구간이다)
|
||||
while i <= j:
|
||||
# 이론적으로 Python의 수는 메모리 크기에 따라 무한히 커질 수 있으므로 큰 수의 범위 초과를 고려할 필요가 없다
|
||||
m = (i + j) // 2 # 중간 인덱스 m을 계산한다
|
||||
if nums[m] < target:
|
||||
i = m + 1 # 이 경우 target은 구간 [m+1, j]에 있다
|
||||
elif nums[m] > target:
|
||||
j = m - 1 # 이 경우 target은 구간 [i, m-1]에 있다
|
||||
else:
|
||||
return m # 목표 원소를 찾았으므로 해당 인덱스를 반환한다
|
||||
return -1 # 목표 원소를 찾지 못했으므로 -1을 반환한다
|
||||
|
||||
|
||||
def binary_search_lcro(nums: list[int], target: int) -> int:
|
||||
"""이진 탐색(왼쪽 끝은 포함하고 오른쪽 끝은 제외하는 구간)"""
|
||||
# 왼쪽 끝만 포함하는 구간 [0, n)을 초기화한다. i는 배열의 첫 원소를, j는 마지막 원소 바로 다음 위치를 가리킨다
|
||||
i, j = 0, len(nums)
|
||||
# 반복하다 탐색 구간이 비면 종료한다(i = j이면 빈 구간이다)
|
||||
while i < j:
|
||||
m = (i + j) // 2 # 중간 인덱스 m을 계산한다
|
||||
if nums[m] < target:
|
||||
i = m + 1 # 이 경우 target은 구간 [m+1, j)에 있다
|
||||
elif nums[m] > target:
|
||||
j = m # 이 경우 target은 구간 [i, m)에 있다
|
||||
else:
|
||||
return m # 목표 원소를 찾았으므로 해당 인덱스를 반환한다
|
||||
return -1 # 목표 원소를 찾지 못했으므로 -1을 반환한다
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
target = 6
|
||||
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
|
||||
# 이진 탐색(양 끝을 포함하는 닫힌 구간)
|
||||
index = binary_search(nums, target)
|
||||
print("목표 원소 6의 인덱스 = ", index)
|
||||
|
||||
# 이진 탐색(왼쪽 끝은 포함하고 오른쪽 끝은 제외하는 구간)
|
||||
index = binary_search_lcro(nums, target)
|
||||
print("목표 원소 6의 인덱스 = ", index)
|
||||
49
ko/codes/python/chapter_searching/binary_search_edge.py
Normal file
49
ko/codes/python/chapter_searching/binary_search_edge.py
Normal 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:
|
||||
"""가장 왼쪽에 있는 target을 이진 탐색"""
|
||||
# target의 삽입 위치를 찾는 것과 같다
|
||||
i = binary_search_insertion(nums, target)
|
||||
# target을 찾지 못했으므로 -1을 반환한다
|
||||
if i == len(nums) or nums[i] != target:
|
||||
return -1
|
||||
# target을 찾았으므로 인덱스 i를 반환한다
|
||||
return i
|
||||
|
||||
|
||||
def binary_search_right_edge(nums: list[int], target: int) -> int:
|
||||
"""가장 오른쪽에 있는 target을 이진 탐색"""
|
||||
# 가장 왼쪽에 있는 target + 1을 찾는 문제로 바꾼다
|
||||
i = binary_search_insertion(nums, target + 1)
|
||||
# j는 가장 오른쪽의 target을 가리키고, i는 target보다 큰 첫 번째 원소를 가리킨다
|
||||
j = i - 1
|
||||
# target을 찾지 못했으므로 -1을 반환한다
|
||||
if j == -1 or nums[j] != target:
|
||||
return -1
|
||||
# target을 찾았으므로 인덱스 j를 반환한다
|
||||
return j
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 중복 원소를 포함하는 배열
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print(f"\n배열 nums = {nums}")
|
||||
|
||||
# 왼쪽 경계와 오른쪽 경계의 이진 탐색
|
||||
for target in [6, 7]:
|
||||
index = binary_search_left_edge(nums, target)
|
||||
print(f"가장 왼쪽 원소 {target}의 인덱스는 {index}이다")
|
||||
index = binary_search_right_edge(nums, target)
|
||||
print(f"가장 오른쪽 원소 {target}의 인덱스는 {index}이다")
|
||||
54
ko/codes/python/chapter_searching/binary_search_insertion.py
Normal file
54
ko/codes/python/chapter_searching/binary_search_insertion.py
Normal 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:
|
||||
"""삽입 위치의 이진 탐색(중복 원소 없음)"""
|
||||
i, j = 0, len(nums) - 1 # 닫힌 구간 [0, n-1]을 초기화한다
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # 중간 인덱스 m을 계산한다
|
||||
if nums[m] < target:
|
||||
i = m + 1 # target은 구간 [m+1, j]에 있다
|
||||
elif nums[m] > target:
|
||||
j = m - 1 # target은 구간 [i, m-1]에 있다
|
||||
else:
|
||||
return m # target을 찾았으므로 삽입 위치 m을 반환한다
|
||||
# target을 찾지 못했으므로 삽입 위치 i를 반환한다
|
||||
return i
|
||||
|
||||
|
||||
def binary_search_insertion(nums: list[int], target: int) -> int:
|
||||
"""삽입 위치의 이진 탐색(중복 원소 있음)"""
|
||||
i, j = 0, len(nums) - 1 # 닫힌 구간 [0, n-1]을 초기화한다
|
||||
while i <= j:
|
||||
m = (i + j) // 2 # 중간 인덱스 m을 계산한다
|
||||
if nums[m] < target:
|
||||
i = m + 1 # target은 구간 [m+1, j]에 있다
|
||||
elif nums[m] > target:
|
||||
j = m - 1 # target은 구간 [i, m-1]에 있다
|
||||
else:
|
||||
j = m - 1 # target보다 작은 가장 오른쪽 원소는 구간 [i, m-1]에 있다
|
||||
# 삽입 위치 i를 반환한다
|
||||
return i
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# 중복 원소가 없는 배열
|
||||
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||||
print(f"\n배열 nums = {nums}")
|
||||
# 삽입 위치의 이진 탐색
|
||||
for target in [6, 9]:
|
||||
index = binary_search_insertion_simple(nums, target)
|
||||
print(f"원소 {target}의 삽입 위치 인덱스는 {index}이다")
|
||||
|
||||
# 중복 원소를 포함하는 배열
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
|
||||
print(f"\n배열 nums = {nums}")
|
||||
# 삽입 위치의 이진 탐색
|
||||
for target in [2, 6, 20]:
|
||||
index = binary_search_insertion(nums, target)
|
||||
print(f"원소 {target}의 삽입 위치 인덱스는 {index}이다")
|
||||
51
ko/codes/python/chapter_searching/hashing_search.py
Normal file
51
ko/codes/python/chapter_searching/hashing_search.py
Normal 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:
|
||||
"""해시 탐색(배열)"""
|
||||
# 해시 테이블의 key: 목표 원소, value: 인덱스
|
||||
# 해시 테이블에 해당 key가 없으면 -1을 반환한다
|
||||
return hmap.get(target, -1)
|
||||
|
||||
|
||||
def hashing_search_linkedlist(
|
||||
hmap: dict[int, ListNode], target: int
|
||||
) -> ListNode | None:
|
||||
"""해시 탐색(연결 리스트)"""
|
||||
# 해시 테이블의 key: 목표 원소, value: 노드 객체
|
||||
# 해시 테이블에 해당 key가 없으면 None을 반환한다
|
||||
return hmap.get(target, None)
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
target = 3
|
||||
|
||||
# 해시 탐색(배열)
|
||||
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
# 해시 테이블 초기화
|
||||
map0 = dict[int, int]()
|
||||
for i in range(len(nums)):
|
||||
map0[nums[i]] = i # key: 원소, value: 인덱스
|
||||
index: int = hashing_search_array(map0, target)
|
||||
print("목표 원소 3의 인덱스 =", index)
|
||||
|
||||
# 해시 탐색(연결 리스트)
|
||||
head: ListNode = list_to_linked_list(nums)
|
||||
# 해시 테이블 초기화
|
||||
map1 = dict[int, ListNode]()
|
||||
while head:
|
||||
map1[head.val] = head # key: 노드 값, value: 노드
|
||||
head = head.next
|
||||
node: ListNode = hashing_search_linkedlist(map1, target)
|
||||
print("목표 노드 값 3에 해당하는 노드 객체", node)
|
||||
45
ko/codes/python/chapter_searching/linear_search.py
Normal file
45
ko/codes/python/chapter_searching/linear_search.py
Normal 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:
|
||||
"""선형 탐색(배열)"""
|
||||
# 배열 순회
|
||||
for i in range(len(nums)):
|
||||
if nums[i] == target: # 목표 원소를 찾았으므로 해당 인덱스를 반환한다
|
||||
return i
|
||||
return -1 # 목표 원소를 찾지 못했으므로 -1을 반환한다
|
||||
|
||||
|
||||
def linear_search_linkedlist(head: ListNode, target: int) -> ListNode | None:
|
||||
"""선형 탐색(연결 리스트)"""
|
||||
# 연결 리스트 순회
|
||||
while head:
|
||||
if head.val == target: # 목표 노드를 찾았으므로 해당 노드를 반환한다
|
||||
return head
|
||||
head = head.next
|
||||
return None # 목표 노드를 찾지 못했으므로 None을 반환한다
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
target = 3
|
||||
|
||||
# 배열에서 선형 탐색을 수행한다
|
||||
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
|
||||
index: int = linear_search_array(nums, target)
|
||||
print("목표 원소 3의 인덱스 =", index)
|
||||
|
||||
# 연결 리스트에서 선형 탐색을 수행한다
|
||||
head: ListNode = list_to_linked_list(nums)
|
||||
node: ListNode | None = linear_search_linkedlist(head, target)
|
||||
print("목표 노드 값 3에 해당하는 노드 객체", node)
|
||||
42
ko/codes/python/chapter_searching/two_sum.py
Normal file
42
ko/codes/python/chapter_searching/two_sum.py
Normal 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]:
|
||||
"""방법 1: 완전 열거"""
|
||||
# 이중 반복문이며 시간 복잡도는 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]:
|
||||
"""방법 2: 보조 해시 테이블"""
|
||||
# 보조 해시 테이블의 공간 복잡도는 O(n)이다
|
||||
dic = {}
|
||||
# 단일 반복문이며 시간 복잡도는 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 []
|
||||
|
||||
|
||||
"""실행 코드"""
|
||||
if __name__ == "__main__":
|
||||
# ======= 테스트 사례 =======
|
||||
nums = [2, 7, 11, 15]
|
||||
target = 13
|
||||
|
||||
# ====== 실행 코드 ======
|
||||
# 방법 1
|
||||
res: list[int] = two_sum_brute_force(nums, target)
|
||||
print("방법 1 res =", res)
|
||||
# 방법 2
|
||||
res: list[int] = two_sum_hash_table(nums, target)
|
||||
print("방법 2 res =", res)
|
||||
Reference in New Issue
Block a user