mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-17 06:00:58 +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,59 @@
|
||||
/**
|
||||
* File: binary_search.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class binary_search {
|
||||
/* Бинарный поиск (двусторонне замкнутый интервал) */
|
||||
int BinarySearch(int[] nums, int target) {
|
||||
// Инициализировать двусторонне замкнутый интервал [0, n-1], то есть i и j указывают на первый и последний элементы массива соответственно
|
||||
int i = 0, j = nums.Length - 1;
|
||||
// Цикл завершается, когда диапазон поиска пуст (при i > j диапазон пуст)
|
||||
while (i <= j) {
|
||||
int m = i + (j - i) / 2; // Вычислить индекс середины m
|
||||
if (nums[m] < target) // Это означает, что target находится в интервале [m+1, j]
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // Это означает, что target находится в интервале [i, m-1]
|
||||
j = m - 1;
|
||||
else // Целевой элемент найден, вернуть его индекс
|
||||
return m;
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Бинарный поиск (лево замкнутый, право открытый интервал) */
|
||||
int BinarySearchLCRO(int[] nums, int target) {
|
||||
// Инициализировать лево замкнутый, право открытый интервал [0, n), то есть i и j указывают на первый элемент массива и позицию сразу за последним элементом соответственно
|
||||
int i = 0, j = nums.Length;
|
||||
// Цикл завершается, когда диапазон поиска пуст (при i = j диапазон пуст)
|
||||
while (i < j) {
|
||||
int m = i + (j - i) / 2; // Вычислить индекс середины m
|
||||
if (nums[m] < target) // Это означает, что target находится в интервале [m+1, j)
|
||||
i = m + 1;
|
||||
else if (nums[m] > target) // Это означает, что target находится в интервале [i, m)
|
||||
j = m;
|
||||
else // Целевой элемент найден, вернуть его индекс
|
||||
return m;
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 6;
|
||||
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
/* Бинарный поиск (двусторонне замкнутый интервал) */
|
||||
int index = BinarySearch(nums, target);
|
||||
Console.WriteLine("Индекс целевого элемента 6 = " + index);
|
||||
|
||||
/* Бинарный поиск (лево замкнутый, право открытый интервал) */
|
||||
index = BinarySearchLCRO(nums, target);
|
||||
Console.WriteLine("Индекс целевого элемента 6 = " + index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: binary_search_edge.cs
|
||||
* Created Time: 2023-08-06
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class binary_search_edge {
|
||||
/* Бинарный поиск самого левого target */
|
||||
int BinarySearchLeftEdge(int[] nums, int target) {
|
||||
// Эквивалентно поиску точки вставки target
|
||||
int i = binary_search_insertion.BinarySearchInsertion(nums, target);
|
||||
// target не найден, вернуть -1
|
||||
if (i == nums.Length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Найти target и вернуть индекс i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Бинарный поиск самого правого target */
|
||||
int BinarySearchRightEdge(int[] nums, int target) {
|
||||
// Преобразовать задачу в поиск самого левого target + 1
|
||||
int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1);
|
||||
// j указывает на самый правый target, а i — на первый элемент больше target
|
||||
int j = i - 1;
|
||||
// target не найден, вернуть -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Найти target и вернуть индекс j
|
||||
return j;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// Массив с повторяющимися элементами
|
||||
int[] nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
Console.WriteLine("\nМассив nums = " + nums.PrintList());
|
||||
|
||||
// Бинарный поиск левой и правой границы
|
||||
foreach (int target in new int[] { 6, 7 }) {
|
||||
int index = BinarySearchLeftEdge(nums, target);
|
||||
Console.WriteLine("Индекс самого левого элемента " + target + " равен " + index);
|
||||
index = BinarySearchRightEdge(nums, target);
|
||||
Console.WriteLine("Индекс самого правого элемента " + target + " равен " + index);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: binary_search_insertion.cs
|
||||
* Created Time: 2023-08-06
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class binary_search_insertion {
|
||||
/* Бинарный поиск точки вставки (без повторяющихся элементов) */
|
||||
public static int BinarySearchInsertionSimple(int[] nums, int target) {
|
||||
int i = 0, j = nums.Length - 1; // Инициализировать двусторонне замкнутый интервал [0, n-1]
|
||||
while (i <= j) {
|
||||
int 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;
|
||||
}
|
||||
|
||||
/* Бинарный поиск точки вставки (с повторяющимися элементами) */
|
||||
public static int BinarySearchInsertion(int[] nums, int target) {
|
||||
int i = 0, j = nums.Length - 1; // Инициализировать двусторонне замкнутый интервал [0, n-1]
|
||||
while (i <= j) {
|
||||
int 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;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// Массив без повторяющихся элементов
|
||||
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
Console.WriteLine("\nМассив nums = " + nums.PrintList());
|
||||
// Бинарный поиск точки вставки
|
||||
foreach (int target in new int[] { 6, 9 }) {
|
||||
int index = BinarySearchInsertionSimple(nums, target);
|
||||
Console.WriteLine("Индекс позиции вставки элемента " + target + " равен " + index);
|
||||
}
|
||||
|
||||
// Массив с повторяющимися элементами
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
Console.WriteLine("\nМассив nums = " + nums.PrintList());
|
||||
// Бинарный поиск точки вставки
|
||||
foreach (int target in new int[] { 2, 6, 20 }) {
|
||||
int index = BinarySearchInsertion(nums, target);
|
||||
Console.WriteLine("Индекс позиции вставки элемента " + target + " равен " + index);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: hashing_search.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class hashing_search {
|
||||
/* Хеш-поиск (массив) */
|
||||
int HashingSearchArray(Dictionary<int, int> map, int target) {
|
||||
// key хеш-таблицы: целевой элемент, value: индекс
|
||||
// Если такого key нет в хеш-таблице, вернуть -1
|
||||
return map.GetValueOrDefault(target, -1);
|
||||
}
|
||||
|
||||
/* Хеш-поиск (связный список) */
|
||||
ListNode? HashingSearchLinkedList(Dictionary<int, ListNode> map, int target) {
|
||||
|
||||
// key хеш-таблицы: значение целевого узла, value: объект узла
|
||||
// Если такого key нет в хеш-таблице, вернуть null
|
||||
return map.GetValueOrDefault(target);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 3;
|
||||
|
||||
/* Хеш-поиск (массив) */
|
||||
int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
// Инициализация хеш-таблицы
|
||||
Dictionary<int, int> map = [];
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
map[nums[i]] = i; // key: элемент, value: индекс
|
||||
}
|
||||
int index = HashingSearchArray(map, target);
|
||||
Console.WriteLine("Индекс целевого элемента 3 = " + index);
|
||||
|
||||
/* Хеш-поиск (связный список) */
|
||||
ListNode? head = ListNode.ArrToLinkedList(nums);
|
||||
// Инициализация хеш-таблицы
|
||||
Dictionary<int, ListNode> map1 = [];
|
||||
while (head != null) {
|
||||
map1[head.val] = head; // key: значение узла, value: узел
|
||||
head = head.next;
|
||||
}
|
||||
ListNode? node = HashingSearchLinkedList(map1, target);
|
||||
Console.WriteLine("Объект узла со значением 3 = " + node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: linear_search.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class linear_search {
|
||||
/* Линейный поиск (массив) */
|
||||
int LinearSearchArray(int[] nums, int target) {
|
||||
// Обход массива
|
||||
for (int i = 0; i < nums.Length; i++) {
|
||||
// Целевой элемент найден, вернуть его индекс
|
||||
if (nums[i] == target)
|
||||
return i;
|
||||
}
|
||||
// Целевой элемент не найден, вернуть -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Линейный поиск (связный список) */
|
||||
ListNode? LinearSearchLinkedList(ListNode? head, int target) {
|
||||
// Обойти связный список
|
||||
while (head != null) {
|
||||
// Найти целевой узел и вернуть его
|
||||
if (head.val == target)
|
||||
return head;
|
||||
head = head.next;
|
||||
}
|
||||
// Целевой узел не найден, вернуть null
|
||||
return null;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int target = 3;
|
||||
|
||||
/* Выполнить линейный поиск в массиве */
|
||||
int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
int index = LinearSearchArray(nums, target);
|
||||
Console.WriteLine("Индекс целевого элемента 3 = " + index);
|
||||
|
||||
/* Выполнить линейный поиск в связном списке */
|
||||
ListNode? head = ListNode.ArrToLinkedList(nums);
|
||||
ListNode? node = LinearSearchLinkedList(head, target);
|
||||
Console.WriteLine("Объект узла со значением 3 = " + node);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: two_sum.cs
|
||||
* Created Time: 2022-12-23
|
||||
* Author: haptear (haptear@hotmail.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_searching;
|
||||
|
||||
public class two_sum {
|
||||
/* Метод 1: полный перебор */
|
||||
int[] TwoSumBruteForce(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// Два вложенных цикла, временная сложность O(n^2)
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
if (nums[i] + nums[j] == target)
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/* Метод 2: вспомогательная хеш-таблица */
|
||||
int[] TwoSumHashTable(int[] nums, int target) {
|
||||
int size = nums.Length;
|
||||
// Вспомогательная хеш-таблица, пространственная сложность O(n)
|
||||
Dictionary<int, int> dic = [];
|
||||
// Один цикл, временная сложность O(n)
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (dic.ContainsKey(target - nums[i])) {
|
||||
return [dic[target - nums[i]], i];
|
||||
}
|
||||
dic.Add(nums[i], i);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
// ======= Test Case =======
|
||||
int[] nums = [2, 7, 11, 15];
|
||||
int target = 13;
|
||||
|
||||
// ====== Основной код ======
|
||||
// Метод 1
|
||||
int[] res = TwoSumBruteForce(nums, target);
|
||||
Console.WriteLine("Результат метода 1 res = " + string.Join(",", res));
|
||||
// Метод 2
|
||||
res = TwoSumHashTable(nums, target);
|
||||
Console.WriteLine("Результат метода 2 res = " + string.Join(",", res));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user