1. Two Sum
Given array of integers, return indices of two numbers that add to target.
Approach: hashmap of value to index, single pass, complement lookup.
#![allow(unused)]
fn main() {
// time O(n), space O(n)
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut num_to_idx: HashMap<i32, i32> = HashMap::new();
for (i, &num) in nums.iter().enumerate() {
let guess = target - num;
if let Some(&x) = num_to_idx.get(&guess) {
return vec![x, i as i32];
}
num_to_idx.insert(num, i as i32);
}
vec![]
}
}