diff --git a/source/lib.rs b/source/lib.rs index 7dd3558..d1b3fad 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -14,6 +14,7 @@ pub mod palindrome_number; pub mod plus_one; pub mod reverse_integer; pub mod roman_to_integer; +pub mod set_mismatch; pub mod two_sum; pub mod valid_anagram; pub mod valid_palindrome; diff --git a/source/set_mismatch/mod.rs b/source/set_mismatch/mod.rs new file mode 100644 index 0000000..880db08 --- /dev/null +++ b/source/set_mismatch/mod.rs @@ -0,0 +1,31 @@ +pub fn find_error_nums(numbers: Vec) -> Vec { + // Uncomment FromIterator in Leetcode since they're using Rust Edition 2018. + // Edition 2021 has this trait in its prelude. + + // use std::iter::FromIterator; + use std::collections::HashSet; + + let range = 1..=numbers.len() as i32; + let mut numbers_set = HashSet::<_>::new(); + + let mut duplicate = 0; + + for number in numbers { + if numbers_set.insert(number) { + continue; + } + + duplicate = number; + } + + let mut missing = 0; + + for number in range { + if !numbers_set.contains(&number) { + missing = number; + break; + } + } + + vec![duplicate, missing] +} diff --git a/tests/set_mismatch.rs b/tests/set_mismatch.rs new file mode 100644 index 0000000..326eccb --- /dev/null +++ b/tests/set_mismatch.rs @@ -0,0 +1,12 @@ +use leetcode::set_mismatch::find_error_nums; + +use test_case::test_case; + +#[test_case(&[1, 2, 2, 4], &[2, 3]; "example 1")] +#[test_case(&[1, 1], &[1, 2]; "example 2")] +#[test_case(&[2, 2], &[2, 1]; "edge 1")] +#[test_case(&[3, 2, 3, 4, 6, 5], &[3, 1]; "edge 2")] +#[test_case(&[3, 2, 2], &[2, 1]; "edge 3")] +fn test_set_mismatch(input: &[i32], expected: &[i32]) { + assert_eq!(find_error_nums(input.to_vec()), expected); +}