From 3c1784fa832bb454a9dd3fde567e293bf98d7d25 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 11 May 2024 10:52:31 +0800 Subject: [PATCH] 20240511 Finished --- src/problem/mod.rs | 3 +- src/problem/p219_contains_duplicate_ii.rs | 45 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 src/problem/p219_contains_duplicate_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index c8bf1df..7b7aa3f 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -127,4 +127,5 @@ mod p290_word_pattern; mod p205_isomorphic_strings; mod p242_valid_anagram; mod p49_group_anagrams; -mod p202_happy_number; \ No newline at end of file +mod p202_happy_number; +mod p219_contains_duplicate_ii; \ No newline at end of file diff --git a/src/problem/p219_contains_duplicate_ii.rs b/src/problem/p219_contains_duplicate_ii.rs new file mode 100644 index 0000000..ba5d31d --- /dev/null +++ b/src/problem/p219_contains_duplicate_ii.rs @@ -0,0 +1,45 @@ +/** + * [219] Contains Duplicate II + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn contains_nearby_duplicate(nums: Vec, k: i32) -> bool { + let mut map = HashMap::new(); + + for (i, v) in nums.iter().enumerate() { + if let Some(last_pos) = map.get_mut(v) { + let distance:i32 = (*last_pos - i as i32); + let distance = distance.abs(); + + if distance > 0 && distance <= k { + return true; + } else { + *last_pos = i as i32; + } + + } else { + map.insert(*v, i as i32); + } + } + + false + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_219() { + assert!(Solution::contains_nearby_duplicate(vec![1,2,3,1], 3)); + assert!(!Solution::contains_nearby_duplicate(vec![1,2,3,1,2,3], 2)); + } +}