mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-02 13:17:14 +00:00
build
This commit is contained in:
@@ -169,7 +169,22 @@ comments: true
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_edge.cs"
|
||||
[class]{binary_search_edge}-[func]{binarySearchLeftEdge}
|
||||
/* 二分查找最左一个元素 */
|
||||
int binarySearchLeftEdge(int[] nums, int target) {
|
||||
int i = 0, j = nums.Length - 1; // 初始化双闭区间 [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // 计算中点索引 m
|
||||
if (nums[m] < target)
|
||||
i = m + 1; // target 在区间 [m+1, j] 中
|
||||
else if (nums[m] > target)
|
||||
j = m - 1; // target 在区间 [i, m-1] 中
|
||||
else
|
||||
j = m - 1; // 首个小于 target 的元素在区间 [i, m-1] 中
|
||||
}
|
||||
if (i == nums.Length || nums[i] != target)
|
||||
return -1; // 未找到目标元素,返回 -1
|
||||
return i;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
@@ -320,7 +335,22 @@ comments: true
|
||||
=== "C#"
|
||||
|
||||
```csharp title="binary_search_edge.cs"
|
||||
[class]{binary_search_edge}-[func]{binarySearchRightEdge}
|
||||
/* 二分查找最右一个元素 */
|
||||
int binarySearchRightEdge(int[] nums, int target) {
|
||||
int i = 0, j = nums.Length - 1; // 初始化双闭区间 [0, n-1]
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // 计算中点索引 m
|
||||
if (nums[m] < target)
|
||||
i = m + 1; // target 在区间 [m+1, j] 中
|
||||
else if (nums[m] > target)
|
||||
j = m - 1; // target 在区间 [i, m-1] 中
|
||||
else
|
||||
i = m + 1; // 首个大于 target 的元素在区间 [m+1, j] 中
|
||||
}
|
||||
if (j < 0 || nums[j] != target)
|
||||
return -1; // 未找到目标元素,返回 -1
|
||||
return j;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
comments: true
|
||||
---
|
||||
|
||||
# 10. 搜索
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
{ width="70%" }
|
||||
|
||||
</div>
|
||||
Reference in New Issue
Block a user