mirror of
https://github.com/rzmk/ladderz.git
synced 2025-12-18 22:49:25 +00:00
feat: add two-sum (PoC)
This commit is contained in:
parent
b46a066dfc
commit
b35539051b
2 changed files with 67 additions and 0 deletions
|
|
@ -54,6 +54,18 @@ pub fn is_anagram2(a: String, b: String) -> bool {
|
|||
letters.into_values().all(|c: i32| c == 0)
|
||||
}
|
||||
|
||||
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
|
||||
let mut seen = HashMap::new();
|
||||
for (i, num) in nums.iter().enumerate() {
|
||||
if seen.contains_key(num) {
|
||||
return vec![i as i32, seen[num]];
|
||||
}
|
||||
let diff = target - num;
|
||||
seen.insert(diff, i as i32);
|
||||
}
|
||||
vec![0, 1]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -71,4 +83,11 @@ mod tests {
|
|||
let expected = true;
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_two_sum() {
|
||||
let result: HashSet<i32> = HashSet::from_iter(two_sum(vec![2, 3, 8, 5], 8));
|
||||
let expected: HashSet<i32> = HashSet::from_iter(vec![1, 3]);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,6 +64,39 @@ pub enum Dsa {
|
|||
#[arg(short = 'r', long)]
|
||||
raw: bool,
|
||||
},
|
||||
/// Returns the indices of two numbers in a vector that sum to a target number.
|
||||
///
|
||||
/// There is an assumption that there must always exist at least two numbers that
|
||||
/// sum to the target number in the given vector of numbers.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ### Input
|
||||
///
|
||||
/// ```bash
|
||||
/// lz dsa two-sum 1,2,3 5
|
||||
/// ```
|
||||
///
|
||||
/// ### Output
|
||||
///
|
||||
/// ```bash
|
||||
/// [1, 2]
|
||||
/// ```
|
||||
///
|
||||
/// ## Raw Output (use `-r` or `--raw`)
|
||||
///
|
||||
/// ```bash
|
||||
/// [1, 2]
|
||||
/// ```
|
||||
TwoSum {
|
||||
/// The vector of numbers as a comma-delimited string.
|
||||
nums: String,
|
||||
/// The number that two numbers from nums must sum to.
|
||||
target: i32,
|
||||
/// Whether or not to return the raw output.
|
||||
#[arg(short = 'r', long)]
|
||||
raw: bool,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn match_dsa(function: Option<Dsa>) {
|
||||
|
|
@ -92,6 +125,21 @@ pub fn match_dsa(function: Option<Dsa>) {
|
|||
)
|
||||
}
|
||||
},
|
||||
Some(Dsa::TwoSum { target, nums, raw }) => {
|
||||
let nums_vec: Vec<i32> = nums
|
||||
.split(',')
|
||||
.map(|num| num.trim())
|
||||
.map(|num| num.parse::<i32>().unwrap())
|
||||
.collect();
|
||||
|
||||
match raw {
|
||||
true => println!("{:?}", two_sum(nums_vec, target)),
|
||||
false => println!(
|
||||
"The pair of indices of the two numbers that sum to {target} is: {:?}.",
|
||||
two_sum(nums_vec, target)
|
||||
),
|
||||
}
|
||||
}
|
||||
None => {
|
||||
println!("Please provide a function to use.");
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue