This commit is contained in:
krahets
2023-06-02 01:35:02 +08:00
parent 8cf488bed2
commit 874e75d92d
17 changed files with 228 additions and 18 deletions
+32 -2
View File
@@ -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"