1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// @Title: 两数之和 (Two Sum)
// @Author: 15816537946@163.com
// @Date: 2020-10-20 14:25:16
// @Runtime: 0 ms
// @Memory: 2.3 MB

use std::collections::HashMap;
impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut hash_map = HashMap::with_capacity(nums.len());
        for (i, &v) in nums.iter().enumerate() {
            let y = target - v;
            if let Some(&c) = hash_map.get(&y) {
                return vec![c as i32, i as i32];
            } else {
                hash_map.insert(v, i);
            }
        }
        vec![]
    }
}