Files
hello-algo/ru/codes/kotlin/chapter_searching/binary_search_edge.kt
Yudong Jin 772183705e Add ru version (#1865)
* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
2026-03-28 04:24:07 +08:00

48 lines
1.8 KiB
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* File: binary_search_edge.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_searching
/* Бинарный поиск самого левого target */
fun binarySearchLeftEdge(nums: IntArray, target: Int): Int {
// Эквивалентно поиску точки вставки target
val i = binarySearchInsertion(nums, target)
// target не найден, вернуть -1
if (i == nums.size || nums[i] != target) {
return -1
}
// Найти target и вернуть индекс i
return i
}
/* Бинарный поиск самого правого target */
fun binarySearchRightEdge(nums: IntArray, target: Int): Int {
// Преобразовать задачу в поиск самого левого target + 1
val i = binarySearchInsertion(nums, target + 1)
// j указывает на самый правый target, а i — на первый элемент больше target
val j = i - 1
// target не найден, вернуть -1
if (j == -1 || nums[j] != target) {
return -1
}
// Найти target и вернуть индекс j
return j
}
/* Driver Code */
fun main() {
// Массив с повторяющимися элементами
val nums = intArrayOf(1, 3, 6, 6, 6, 6, 6, 10, 12, 15)
println("\nМассив nums = ${nums.contentToString()}")
// Бинарный поиск левой и правой границы
for (target in intArrayOf(6, 7)) {
var index = binarySearchLeftEdge(nums, target)
println("Индекс самого левого элемента $target равен $index")
index = binarySearchRightEdge(nums, target)
println("Индекс самого правого элемента $target равен $index")
}
}