219. Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Rust Solution
struct Solution;
use std::collections::HashSet;
impl Solution {
fn contains_nearby_duplicate(nums: Vec<i32>, k: i32) -> bool {
let mut hs: HashSet<i32> = HashSet::new();
let n = nums.len();
let k = k as usize;
for i in 0..n {
let x = nums[i];
if hs.contains(&x) {
return true;
} else {
hs.insert(x);
if hs.len() > k {
hs.remove(&nums[i - k]);
}
}
}
false
}
}
#[test]
fn test() {
let nums = vec![1, 2, 3, 1];
assert_eq!(Solution::contains_nearby_duplicate(nums, 3), true);
let nums = vec![1, 0, 1, 1];
assert_eq!(Solution::contains_nearby_duplicate(nums, 1), true);
let nums = vec![1, 2, 3, 1, 2, 3];
assert_eq!(Solution::contains_nearby_duplicate(nums, 2), false);
}
Having problems with this solution? Click here to submit an issue on github.