This commit is contained in:
krahets
2024-05-15 19:00:27 +08:00
parent bd54cd096b
commit e434a3343c
36 changed files with 402 additions and 107 deletions

View File

@@ -422,9 +422,32 @@ comments: true
=== "Ruby"
```ruby title="binary_search_recur.rb"
[class]{}-[func]{dfs}
### 二分查找:问题 f(i, j) ###
def dfs(nums, target, i, j)
# 若区间为空,代表无目标元素,则返回 -1
return -1 if i > j
# 计算中点索引 m
m = (i + j) / 2
[class]{}-[func]{binary_search}
if nums[m] < target
# 递归子问题 f(m+1, j)
return dfs(nums, target, m + 1, j)
elsif nums[m] > target
# 递归子问题 f(i, m-1)
return dfs(nums, target, i, m - 1)
else
# 找到目标元素,返回其索引
return m
end
end
### 二分查找 ###
def binary_search(nums, target)
n = nums.length
# 求解问题 f(0, n-1)
dfs(nums, target, 0, n - 1)
end
```
=== "Zig"