Solve contains-duplicate-ii.
This commit is contained in:
parent
76ffc98ed4
commit
8f4e167d27
|
@ -0,0 +1,15 @@
|
|||
pub fn contains_nearby_duplicate(numbers: Vec<i32>, 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)
|
||||
}
|
|
@ -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;
|
||||
|
|
|
@ -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::<Vec<i32>>(), 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);
|
||||
}
|
Loading…
Reference in New Issue