From 2f67f65aeb40760d042c4feb882e8f907588cc1c Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Tue, 5 Sep 2023 21:25:29 +0400 Subject: Решение с хэш-таблицей MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- two-sum/README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 two-sum/README.md (limited to 'two-sum') diff --git a/two-sum/README.md b/two-sum/README.md new file mode 100644 index 0000000..28150e9 --- /dev/null +++ b/two-sum/README.md @@ -0,0 +1,26 @@ +# Two Sum + +## Использование хэщ-таблицы + +В этом решении используется хэш-таблица. + +- Сложность: `O(n)`. +- Плюс: Скорость. +- Минус: Память. + +```rust +pub fn two_sum(nums: Vec, target: i32) -> Vec { + let mut hash: std::collections::HashMap = std::collections::HashMap::new(); + + for (i, x) in nums.iter().enumerate() { + if hash.contains_key(x) { + return vec![*hash.get(x).unwrap() as i32, i as i32]; + } + + let res = target - x; + hash.insert(res, i); + } + + panic!("No solution found") +} +``` \ No newline at end of file -- cgit v1.2.3