Add Python code (Chapter of searching)

to the docs.
This commit is contained in:
Yudong Jin
2022-12-04 01:43:58 +08:00
parent e5563b3964
commit 8e34be0641
6 changed files with 106 additions and 51 deletions

View File

@@ -47,7 +47,13 @@ comments: true
=== "Python"
```python title="linear_search.py"
""" 线性查找(数组) """
def linear_search(nums, target):
# 遍历数组
for i in range(len(nums)):
if nums[i] == target: # 找到目标元素,返回其索引
return i
return -1 # 未找到目标元素,返回 -1
```
=== "Go"
@@ -119,7 +125,14 @@ comments: true
=== "Python"
```python title="linear_search.py"
""" 线性查找(链表) """
def linear_search1(head, target):
# 遍历链表
while head:
if head.val == target: # 找到目标结点,返回之
return head
head = head.next
return None # 未找到目标结点,返回 None
```
=== "Go"