aboutsummaryrefslogtreecommitdiff
path: root/two-sum/README.md
blob: 28150e90e3b3e77af52c14e29f52e1b5de1deea5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Two Sum

## Использование хэщ-таблицы

В этом решении используется хэш-таблица.

- Сложность: `O(n)`.
- Плюс: Скорость.
- Минус: Память.

```rust
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut hash: std::collections::HashMap<i32, usize> = 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")
}
```