Skip to content

Instantly share code, notes, and snippets.

@uztbt
Last active April 25, 2022 15:26
Show Gist options
  • Save uztbt/2c897b38d97833164df90ed324f457f7 to your computer and use it in GitHub Desktop.
Save uztbt/2c897b38d97833164df90ed324f457f7 to your computer and use it in GitHub Desktop.
My first competitive program in Rust - https://leetcode.com/problems/two-sum/
use std::collections::HashMap;
struct Solution();
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut hm: HashMap<i32, Vec<i32>> = HashMap::new();
for i in 0..nums.len() {
hm.entry(nums[i]).or_insert(vec![]).push(i as i32);
}
for num in nums {
let other = target - num;
if num == other {
let num_indices = hm.get(&num).unwrap();
if num_indices.len() > 1 {
return num_indices.clone();
}
} else {
match hm.get(&other) {
Some(_) => return vec![hm.get(&num).unwrap()[0], hm.get(&other).unwrap()[0]],
None => {
continue;
}
}
}
}
panic!();
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn succeess() {
let want = vec![2, 8];
let got = Solution::two_sum(vec![0, 4, 2, 5, 2, 5, 5, 2, 1], 3);
assert_eq!(got, want);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment