From 8f4e167d2797c74087f40703d0c94759f918f1bd Mon Sep 17 00:00:00 2001 From: Bauke Date: Mon, 11 Apr 2022 14:02:46 +0200 Subject: [PATCH] Solve contains-duplicate-ii. --- source/contains_duplicate_ii/mod.rs | 15 +++++++++++++++ source/lib.rs | 1 + tests/contains_duplicate_ii.rs | 12 ++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 source/contains_duplicate_ii/mod.rs create mode 100644 tests/contains_duplicate_ii.rs diff --git a/source/contains_duplicate_ii/mod.rs b/source/contains_duplicate_ii/mod.rs new file mode 100644 index 0000000..ffd2e3c --- /dev/null +++ b/source/contains_duplicate_ii/mod.rs @@ -0,0 +1,15 @@ +pub fn contains_nearby_duplicate(numbers: Vec, range: i32) -> bool { + // Uncomment FromIterator in Leetcode since they're using Rust Edition 2018. + // Edition 2021 has this trait in its prelude. + + // use std::iter::FromIterator; + fn contains_duplicate(numbers: &[i32]) -> bool { + std::collections::HashSet::<_>::from_iter(numbers).len() != numbers.len() + } + + contains_duplicate(&numbers) + && numbers + .as_slice() + .windows(std::cmp::min((range + 1) as usize, numbers.len())) + .any(contains_duplicate) +} diff --git a/source/lib.rs b/source/lib.rs index 9c29e04..7ad9cc0 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1,5 +1,6 @@ pub mod add_binary; pub mod contains_duplicate; +pub mod contains_duplicate_ii; pub mod excel_sheet_column_number; pub mod excel_sheet_column_title; pub mod implement_strstr; diff --git a/tests/contains_duplicate_ii.rs b/tests/contains_duplicate_ii.rs new file mode 100644 index 0000000..e617d1e --- /dev/null +++ b/tests/contains_duplicate_ii.rs @@ -0,0 +1,12 @@ +use leetcode::contains_duplicate_ii::contains_nearby_duplicate; + +use test_case::test_case; + +#[test_case(&[1, 2, 3, 1], 3, true; "example 1")] +#[test_case(&[1, 0, 1, 1], 1, true; "example 2")] +#[test_case(&[1, 2, 3, 1, 2, 3], 2, false; "example 3")] +#[test_case(&[99, 99], 2, true; "range higher than numbers")] +#[test_case(&(-25000..=30000).collect::>(), 35000, false; "massive input")] +fn test_contains_duplicate_ii(numbers: &[i32], range: i32, expected: bool) { + assert_eq!(contains_nearby_duplicate(numbers.to_vec(), range), expected); +}