This commit is contained in:
krahets
2024-03-25 22:43:12 +08:00
parent 22017aa8e5
commit 87af663929
70 changed files with 7428 additions and 32 deletions

View File

@ -268,6 +268,28 @@ comments: true
}
```
=== "Kotlin"
```kotlin title="binary_search_insertion.kt"
/* 二分查找插入点(无重复元素) */
fun binarySearchInsertionSimple(nums: IntArray, target: Int): Int {
var i = 0
var j = nums.size - 1 // 初始化双闭区间 [0, n-1]
while (i <= j) {
val 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 {
return m // 找到 target ,返回插入点 m
}
}
// 未找到 target ,返回插入点 i
return i
}
```
=== "Zig"
```zig title="binary_search_insertion.zig"
@ -572,6 +594,28 @@ comments: true
}
```
=== "Kotlin"
```kotlin title="binary_search_insertion.kt"
/* 二分查找插入点(存在重复元素) */
fun binarySearchInsertion(nums: IntArray, target: Int): Int {
var i = 0
var j = nums.size - 1 // 初始化双闭区间 [0, n-1]
while (i <= j) {
val 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] 中
}
}
// 返回插入点 i
return i
}
```
=== "Zig"
```zig title="binary_search_insertion.zig"