leet-code/two-sum/sol.rs

16 lines
477 B
Rust

use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut done: HashMap<i32, i32> = HashMap::new();
nums
.into_iter()
.enumerate()
.find_map(|(i2, n2)|
done.get(&n2)
.and_then(|i1| Some(vec![*i1, i2 as i32]))
.or_else(|| done.insert(target-n2, i2 as i32).and(None))
)
.unwrap()
}
}