Files
hello-algo/ru/codes/swift/chapter_searching/binary_search_edge.swift
Yudong Jin 71a773df64 fix(ru): align proofreading corrections with the Simplified Chinese original (#2004)
* docs(ru): correct proofreading issues in prose and code examples

* docs(ru): align proofreading edits with Simplified Chinese source

* fix(ru): repair generated Zig statements and complete comment translations
2026-10-27 18:19:11 +08:00

52 lines
2.0 KiB
Swift
Raw 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.swift
* Created Time: 2023-08-06
* Author: nuomi1 (nuomi1@qq.com)
*/
import binary_search_insertion_target
/* Двоичный поиск самого левого элемента target */
func binarySearchLeftEdge(nums: [Int], target: Int) -> Int {
// Эквивалентно поиску точки вставки target
let i = binarySearchInsertion(nums: nums, target: target)
// target не найден, вернуть -1
if i == nums.endIndex || nums[i] != target {
return -1
}
// target найден, возвращается индекс i
return i
}
/* Двоичный поиск самого правого элемента 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
}
@main
enum BinarySearchEdge {
/* Driver Code */
static func main() {
// Массив с повторяющимися элементами
let nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
print("\nМассив nums = \(nums)")
// Двоичный поиск левой и правой границы
for target in [6, 7] {
var index = binarySearchLeftEdge(nums: nums, target: target)
print("Индекс самого левого элемента \(target) равен \(index)")
index = binarySearchRightEdge(nums: nums, target: target)
print("Индекс самого правого элемента \(target) равен \(index)")
}
}
}