mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-04 14:17:14 +00:00
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
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* File: binary_search.rs
|
||||
* Created Time: 2023-02-05
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
/* Бинарный поиск (двусторонне замкнутый интервал) */
|
||||
fn binary_search(nums: &[i32], target: i32) -> i32 {
|
||||
// Инициализировать двусторонне замкнутый интервал [0, n-1], то есть i и j указывают на первый и последний элементы массива соответственно
|
||||
let mut i = 0;
|
||||
let mut j = nums.len() as i32 - 1;
|
||||
// Цикл завершается, когда диапазон поиска пуст (при i > j диапазон пуст)
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2; // Вычислить индекс середины m
|
||||
if nums[m as usize] < target {
|
||||
// Это означает, что target находится в интервале [m+1, j]
|
||||
i = m + 1;
|
||||
} else if nums[m as usize] > target {
|
||||
// Это означает, что target находится в интервале [i, m-1]
|
||||
j = m - 1;
|
||||
} else {
|
||||
// Целевой элемент найден, вернуть его индекс
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Бинарный поиск (лево замкнутый, право открытый интервал) */
|
||||
fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
|
||||
// Инициализировать лево замкнутый, право открытый интервал [0, n), то есть i и j указывают на первый элемент массива и позицию сразу за последним элементом соответственно
|
||||
let mut i = 0;
|
||||
let mut j = nums.len() as i32;
|
||||
// Цикл завершается, когда диапазон поиска пуст (при i = j диапазон пуст)
|
||||
while i < j {
|
||||
let m = i + (j - i) / 2; // Вычислить индекс середины m
|
||||
if nums[m as usize] < target {
|
||||
// Это означает, что target находится в интервале [m+1, j)
|
||||
i = m + 1;
|
||||
} else if nums[m as usize] > target {
|
||||
// Это означает, что target находится в интервале [i, m)
|
||||
j = m;
|
||||
} else {
|
||||
// Целевой элемент найден, вернуть его индекс
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
pub fn main() {
|
||||
let target = 6;
|
||||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
// Бинарный поиск (двусторонне замкнутый интервал)
|
||||
let mut index = binary_search(&nums, target);
|
||||
println!("Индекс целевого элемента 6 = {index}");
|
||||
|
||||
// Бинарный поиск (лево замкнутый, право открытый интервал)
|
||||
index = binary_search_lcro(&nums, target);
|
||||
println!("Индекс целевого элемента 6 = {index}");
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* File: binary_search_insertion.rs
|
||||
* Created Time: 2023-08-30
|
||||
* Author: night-cruise (2586447362@qq.com)
|
||||
*/
|
||||
#![allow(unused)]
|
||||
|
||||
/* Бинарный поиск точки вставки (без повторяющихся элементов) */
|
||||
fn binary_search_insertion_simple(nums: &[i32], target: i32) -> i32 {
|
||||
let (mut i, mut j) = (0, nums.len() as i32 - 1); // Инициализировать двусторонне замкнутый интервал [0, n-1]
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2; // Вычислить индекс середины m
|
||||
if nums[m as usize] < target {
|
||||
i = m + 1; // target находится в интервале [m+1, j]
|
||||
} else if nums[m as usize] > target {
|
||||
j = m - 1; // target находится в интервале [i, m-1]
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
// target не найден, вернуть точку вставки i
|
||||
i
|
||||
}
|
||||
|
||||
/* Бинарный поиск точки вставки (с повторяющимися элементами) */
|
||||
pub fn binary_search_insertion(nums: &[i32], target: i32) -> i32 {
|
||||
let (mut i, mut j) = (0, nums.len() as i32 - 1); // Инициализировать двусторонне замкнутый интервал [0, n-1]
|
||||
while i <= j {
|
||||
let m = i + (j - i) / 2; // Вычислить индекс середины m
|
||||
if nums[m as usize] < target {
|
||||
i = m + 1; // target находится в интервале [m+1, j]
|
||||
} else if nums[m as usize] > target {
|
||||
j = m - 1; // target находится в интервале [i, m-1]
|
||||
} else {
|
||||
j = m - 1; // Первый элемент меньше target находится в интервале [i, m-1]
|
||||
}
|
||||
}
|
||||
// Вернуть точку вставки i
|
||||
i
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
fn main() {
|
||||
// Массив без повторяющихся элементов
|
||||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
println!("\nМассив nums = {:?}", nums);
|
||||
// Бинарный поиск точки вставки
|
||||
for target in [6, 9] {
|
||||
let index = binary_search_insertion_simple(&nums, target);
|
||||
println!("Индекс позиции вставки элемента {} равен {}", target, index);
|
||||
}
|
||||
|
||||
// Массив с повторяющимися элементами
|
||||
let nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
println!("\nМассив nums = {:?}", nums);
|
||||
// Бинарный поиск точки вставки
|
||||
for target in [2, 6, 20] {
|
||||
let index = binary_search_insertion(&nums, target);
|
||||
println!("Индекс позиции вставки элемента {} равен {}", target, index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* File: hashing_search.rs
|
||||
* Created Time: 2023-07-09
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
use hello_algo_rust::include::ListNode;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
/* Хеш-поиск (массив) */
|
||||
fn hashing_search_array<'a>(map: &'a HashMap<i32, usize>, target: i32) -> Option<&'a usize> {
|
||||
// key хеш-таблицы: целевой элемент, value: индекс
|
||||
// Если такого key нет в хеш-таблице, вернуть None
|
||||
map.get(&target)
|
||||
}
|
||||
|
||||
/* Хеш-поиск (связный список) */
|
||||
fn hashing_search_linked_list(
|
||||
map: &HashMap<i32, Rc<RefCell<ListNode<i32>>>>,
|
||||
target: i32,
|
||||
) -> Option<&Rc<RefCell<ListNode<i32>>>> {
|
||||
// key хеш-таблицы: значение целевого узла, value: объект узла
|
||||
// Если такого key нет в хеш-таблице, вернуть None
|
||||
map.get(&target)
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
pub fn main() {
|
||||
let target = 3;
|
||||
|
||||
/* Хеш-поиск (массив) */
|
||||
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
// Инициализация хеш-таблицы
|
||||
let mut map = HashMap::new();
|
||||
for (i, num) in nums.iter().enumerate() {
|
||||
map.insert(*num, i); // key: элемент, value: индекс
|
||||
}
|
||||
let index = hashing_search_array(&map, target);
|
||||
println!("Индекс целевого элемента 3 = {}", index.unwrap());
|
||||
|
||||
/* Хеш-поиск (связный список) */
|
||||
let head = ListNode::arr_to_linked_list(&nums);
|
||||
// Инициализировать хеш-таблицу
|
||||
// let mut map1 = HashMap::new();
|
||||
let map1 = ListNode::linked_list_to_hashmap(head);
|
||||
let node = hashing_search_linked_list(&map1, target);
|
||||
println!("Объект узла со значением 3 = {:?}", node);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* File: linear_search.rs
|
||||
* Created Time: 2023-07-09
|
||||
* Author: codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
use hello_algo_rust::include::ListNode;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/* Линейный поиск (массив) */
|
||||
fn linear_search_array(nums: &[i32], target: i32) -> i32 {
|
||||
// Обход массива
|
||||
for (i, num) in nums.iter().enumerate() {
|
||||
// Целевой элемент найден, вернуть его индекс
|
||||
if num == &target {
|
||||
return i as i32;
|
||||
}
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Линейный поиск (связный список) */
|
||||
fn linear_search_linked_list(
|
||||
head: Rc<RefCell<ListNode<i32>>>,
|
||||
target: i32,
|
||||
) -> Option<Rc<RefCell<ListNode<i32>>>> {
|
||||
// Найти целевой узел и вернуть его
|
||||
if head.borrow().val == target {
|
||||
return Some(head);
|
||||
};
|
||||
// Найти целевой узел и вернуть его
|
||||
if let Some(node) = &head.borrow_mut().next {
|
||||
return linear_search_linked_list(node.clone(), target);
|
||||
}
|
||||
// Целевой узел не найден, вернуть None
|
||||
return None;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
pub fn main() {
|
||||
let target = 3;
|
||||
|
||||
/* Выполнить линейный поиск в массиве */
|
||||
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
let index = linear_search_array(&nums, target);
|
||||
println!("Индекс целевого элемента 3 = {}", index);
|
||||
|
||||
/* Выполнить линейный поиск в связном списке */
|
||||
let head = ListNode::arr_to_linked_list(&nums);
|
||||
let node = linear_search_linked_list(head.unwrap(), target);
|
||||
println!("Объект узла со значением 3 = {:?}", node);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* File: two_sum.rs
|
||||
* Created Time: 2023-01-14
|
||||
* Author: xBLACICEx (xBLACKICEx@outlook.com), codingonion (coderonion@gmail.com)
|
||||
*/
|
||||
|
||||
use hello_algo_rust::include::print_util;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/* Метод 1: полный перебор */
|
||||
pub fn two_sum_brute_force(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
let size = nums.len();
|
||||
// Два вложенных цикла, временная сложность O(n^2)
|
||||
for i in 0..size - 1 {
|
||||
for j in i + 1..size {
|
||||
if nums[i] + nums[j] == target {
|
||||
return Some(vec![i as i32, j as i32]);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/* Метод 2: вспомогательная хеш-таблица */
|
||||
pub fn two_sum_hash_table(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
||||
// Вспомогательная хеш-таблица, пространственная сложность O(n)
|
||||
let mut dic = HashMap::new();
|
||||
// Один цикл, временная сложность O(n)
|
||||
for (i, num) in nums.iter().enumerate() {
|
||||
match dic.get(&(target - num)) {
|
||||
Some(v) => return Some(vec![*v as i32, i as i32]),
|
||||
None => dic.insert(num, i as i32),
|
||||
};
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// ======= Test Case =======
|
||||
let nums = vec![2, 7, 11, 15];
|
||||
let target = 13;
|
||||
|
||||
// ====== Основной код ======
|
||||
// Метод 1
|
||||
let res = two_sum_brute_force(&nums, target).unwrap();
|
||||
print!("Результат метода 1 res = ");
|
||||
print_util::print_array(&res);
|
||||
// Метод 2
|
||||
let res = two_sum_hash_table(&nums, target).unwrap();
|
||||
print!("\nРезультат метода 2 res = ");
|
||||
print_util::print_array(&res);
|
||||
}
|
||||
Reference in New Issue
Block a user