Skip to content

Commit

Permalink
Add problem 2215: Find the Difference of Two Arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Mar 18, 2024
1 parent 398723c commit f6a9dd1
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1481,6 +1481,7 @@ pub mod problem_2186_minimum_number_of_steps_to_make_two_strings_anagram_ii;
pub mod problem_2190_most_frequent_number_following_key_in_an_array;
pub mod problem_2194_cells_in_a_range_on_an_excel_sheet;
pub mod problem_2206_divide_array_into_equal_pairs;
pub mod problem_2215_find_the_difference_of_two_arrays;

#[cfg(test)]
mod test_utilities;
33 changes: 33 additions & 0 deletions src/problem_2215_find_the_difference_of_two_arrays/hash_set.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::collections::HashSet;

impl Solution {
pub fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>> {
let nums1 = nums1.into_iter().collect::<HashSet<_>>();
let nums2 = nums2.into_iter().collect::<HashSet<_>>();

vec![
nums1.difference(&nums2).copied().collect(),
nums2.difference(&nums1).copied().collect(),
]
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>> {
Self::find_difference(nums1, nums2)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
30 changes: 30 additions & 0 deletions src/problem_2215_find_the_difference_of_two_arrays/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
pub mod hash_set;

pub trait Solution {
fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>>;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(
(&[1, 2, 3] as &[_], &[2, 4, 6] as &[_]),
[&[1, 3] as &[_], &[4, 6] as &[_]],
),
((&[1, 2, 3, 3], &[1, 1, 2, 2]), [&[3] as &[_], &[] as &[_]]),
];

for ((nums1, nums2), expected) in test_cases {
let mut result = S::find_difference(nums1.to_vec(), nums2.to_vec());

for value in &mut result {
value.sort_unstable();
}

assert_eq!(result, expected.map(Vec::from),);
}
}
}

0 comments on commit f6a9dd1

Please sign in to comment.