Skip to content

Commit

Permalink
solution of two_sum
Browse files Browse the repository at this point in the history
  • Loading branch information
tednaaa committed Sep 3, 2024
1 parent cc4c4b4 commit 37eb871
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,9 @@ pedantic = "warn"
nursery = "warn"

[workspace]
members = ["crates/contains_duplicate", "crates/valid_anagram"]
members = [
"crates/contains_duplicate",
"crates/two_sum",
"crates/valid_anagram",
]
resolver = "2"
9 changes: 9 additions & 0 deletions crates/two_sum/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "two_sum"
version = "0.1.0"
edition = "2021"

[dependencies]

[lints]
workspace = true
42 changes: 42 additions & 0 deletions crates/two_sum/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::collections::HashMap;

#[must_use]
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map = HashMap::new();

for (i, number) in nums.into_iter().enumerate() {
let diff = target - number;

if let Some(&j) = map.get(&diff) {
#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
return vec![i as i32, j as i32];
}

map.insert(number, i);
}

unreachable!()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn case_1() {
let result = two_sum(vec![2, 7, 11, 15], 9);
assert_eq!(result, [0, 1]);
}

#[test]
fn case_2() {
let result = two_sum(vec![3, 2, 4], 6);
assert_eq!(result, [1, 2]);
}

#[test]
fn case_3() {
let result = two_sum(vec![3, 3], 6);
assert_eq!(result, [0, 1]);
}
}

0 comments on commit 37eb871

Please sign in to comment.