This commit is contained in:
krahets
2023-08-06 23:19:07 +08:00
parent fafdebb75c
commit 48adefba25
8 changed files with 136 additions and 33 deletions
+49 -5
View File
@@ -11,7 +11,7 @@ status: new
给定一个长度为 $n$ 的有序数组 `nums` ,数组可能包含重复元素。请返回数组中最左一个元素 `target` 的索引。若数组中不包含该元素,则返回 $-1$ 。
回忆二分查找插入点的方法,搜索完成后$i$ 指向最左一个 `target` ,**因此查找插入点本质上是在查找最左一个 `target` 的索引**。
回忆二分查找插入点的方法,搜索完成后 $i$ 指向最左一个 `target` ,**因此查找插入点本质上是在查找最左一个 `target` 的索引**。
考虑通过查找插入点的函数实现查找左边界。请注意,数组中可能不包含 `target` ,此时有两种可能:
@@ -93,13 +93,33 @@ status: new
=== "C#"
```csharp title="binary_search_edge.cs"
[class]{binary_search_edge}-[func]{binarySearchLeftEdge}
/* 二分查找最左一个 target */
int binarySearchLeftEdge(int[] nums, int target) {
// 等价于查找 target 的插入点
int i = binary_search_insertion.binarySearchInsertion(nums, target);
// 未找到 target ,返回 -1
if (i == nums.Length || nums[i] != target) {
return -1;
}
// 找到 target ,返回索引 i
return i;
}
```
=== "Swift"
```swift title="binary_search_edge.swift"
[class]{}-[func]{binarySearchLeftEdge}
/* 二分查找最左一个 target */
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
// 等价于查找 target 的插入点
let i = binarySearchInsertion(nums: nums, target: target)
// 未找到 target ,返回 -1
if i == nums.count || nums[i] != target {
return -1
}
// 找到 target ,返回索引 i
return i
}
```
=== "Zig"
@@ -217,13 +237,37 @@ status: new
=== "C#"
```csharp title="binary_search_edge.cs"
[class]{binary_search_edge}-[func]{binarySearchRightEdge}
/* 二分查找最右一个 target */
int binarySearchRightEdge(int[] nums, int target) {
// 转化为查找最左一个 target + 1
int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
// j 指向最右一个 target ,i 指向首个大于 target 的元素
int j = i - 1;
// 未找到 target ,返回 -1
if (j == -1 || nums[j] != target) {
return -1;
}
// 找到 target ,返回索引 j
return j;
}
```
=== "Swift"
```swift title="binary_search_edge.swift"
[class]{}-[func]{binarySearchRightEdge}
/* 二分查找最右一个 target */
func binarySearchRightEdge(nums: [Int], target: Int) -> Int {
// 转化为查找最左一个 target + 1
let i = binarySearchInsertion(nums: nums, target: target + 1)
// j 指向最右一个 target ,i 指向首个大于 target 的元素
let j = i - 1
// 未找到 target ,返回 -1
if j == -1 || nums[j] != target {
return -1
}
// 找到 target ,返回索引 j
return j
}
```
=== "Zig"