20240511 Finished

This commit is contained in:
jackfiled 2024-05-11 10:52:31 +08:00
parent 14adc38396
commit 3c1784fa83
2 changed files with 47 additions and 1 deletions

View File

@ -127,4 +127,5 @@ mod p290_word_pattern;
mod p205_isomorphic_strings; mod p205_isomorphic_strings;
mod p242_valid_anagram; mod p242_valid_anagram;
mod p49_group_anagrams; mod p49_group_anagrams;
mod p202_happy_number; mod p202_happy_number;
mod p219_contains_duplicate_ii;

View File

@ -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<i32>, 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));
}
}