leetcode

Log | Files | Refs | README

commit 5933f45e05ef14b0af8a78f1aaeaba25dd585537
Author: ling0x <ling0x@users.noreply.github.com>
Date:   Sat, 11 Apr 2026 02:44:48 +0100

initial commit

Diffstat:
A.gitignore | 1+
ACargo.lock | 7+++++++
ACargo.toml | 6++++++
Asrc/hash_table/mod.rs | 1+
Asrc/hash_table/two_sum.rs | 39+++++++++++++++++++++++++++++++++++++++
Asrc/lib.rs | 1+
Asrc/main.rs | 3+++
7 files changed, 58 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "leetcode" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "leetcode" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/hash_table/mod.rs b/src/hash_table/mod.rs @@ -0,0 +1 @@ +pub mod two_sum; diff --git a/src/hash_table/two_sum.rs b/src/hash_table/two_sum.rs @@ -0,0 +1,39 @@ +use std::collections::HashSet; + +// First try +pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { + let mut result = HashSet::<i32>::new(); + + nums.iter().enumerate().for_each(|(idx, x)| { + let pair = nums + .iter() + .enumerate() + .find(|(idx2, y)| *y + x == target && &idx != idx2); + if let Some((idx2, y)) = pair { + result.insert(idx as i32); + result.insert(idx2 as i32); + println!("result: {} + {:?} = {}", x, y, target); + } + }); + + println!("{:#?}", result); + result.into_iter().collect() +} + +#[cfg(test)] +mod tests { + use crate::hash_table::two_sum::two_sum; + + #[test] + fn two_sum_test_1() { + two_sum(vec![2, 7, 11, 15], 9); + } + #[test] + fn two_sum_test_2() { + two_sum(vec![3, 2, 3], 6); + } + #[test] + fn two_sum_test_3() { + two_sum(vec![3, 2, 4], 6); + } +} diff --git a/src/lib.rs b/src/lib.rs @@ -0,0 +1 @@ +pub mod hash_table; diff --git a/src/main.rs b/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Cargo test all the leetcode cases"); +}