0001.两数之和
方法一:哈希表
时间复杂度 $O(n)$,空间复杂度 $O(n)$。
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
use std::collections::HashMap;
let mut map = HashMap::new();
for (i, num) in nums.iter().enumerate() {
let complement = target - num;
if map.contains_key(&complement) {
return vec![*map.get(&complement).unwrap() as i32, i as i32];
}
map.insert(num, i);
}
vec![]
}
}