Files
hello-algo/ru/codes/rust/chapter_searching/binary_search_edge.rs
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

51 lines
1.9 KiB
Rust
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.rs
* Created Time: 2023-08-30
* Author: night-cruise (2586447362@qq.com)
*/
mod binary_search_insertion;
use binary_search_insertion::binary_search_insertion;
/* Двоичный поиск самого левого элемента target */
fn binary_search_left_edge(nums: &[i32], target: i32) -> i32 {
// Эквивалентно поиску точки вставки target
let i = binary_search_insertion(nums, target);
// target не найден, вернуть -1
if i == nums.len() as i32 || nums[i as usize] != target {
return -1;
}
// target найден, возвращается индекс i
i
}
/* Двоичный поиск самого правого элемента target */
fn binary_search_right_edge(nums: &[i32], target: i32) -> i32 {
// Преобразовать задачу в поиск самого левого target + 1
let i = binary_search_insertion(nums, target + 1);
// j указывает на самый правый target, а i — на первый элемент больше target
let j = i - 1;
// target не найден, вернуть -1
if j == -1 || nums[j as usize] != target {
return -1;
}
// target найден, возвращается индекс j
j
}
/* Driver Code */
fn main() {
// Массив с повторяющимися элементами
let nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
println!("\nМассив nums = {:?}", nums);
// Двоичный поиск левой и правой границы
for target in [6, 7] {
let index = binary_search_left_edge(&nums, target);
println!("Индекс самого левого элемента {} равен {}", target, index);
let index = binary_search_right_edge(&nums, target);
println!("Индекс самого правого элемента {} равен {}", target, index);
}
}