Skip to content

Instantly share code, notes, and snippets.

@aloucks
Created March 10, 2022 16:40
Show Gist options
  • Save aloucks/e4ec1e7874907edb24c51ec7c6a123ea to your computer and use it in GitHub Desktop.
Save aloucks/e4ec1e7874907edb24c51ec7c6a123ea to your computer and use it in GitHub Desktop.
two_sum.rs
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map = HashMap::with_capacity(nums.len());
for (i, n) in nums.iter().copied().enumerate() {
let i = i as i32;
let r = target - n;
if let Some(j) = map.get(&r) {
let j = *j;
return vec![i, j];
} else {
map.insert(n, i);
}
}
panic!("no solution")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment