DEV Community

Discussion on: Daily Challenge #63- Two Sum

Collapse
 
brightone profile image
Oleksii Filonenko

Inspired by Michael Kohl's solution in F# (O(n) rules!), I did the same thing in Rust. All the credit to him :)

fn two_sum(ns: &[i32], sum: i32) -> Option<(usize, usize)> {
    let mut map = HashMap::new();
    for (i, &n) in ns.iter().enumerate() {
        let diff = sum - n;
        if let Some(&j) = map.get(&diff) {
            return Some((j, i));
        }
        map.insert(n, i);
    }
    None
}