Skip to content

Commit

Permalink
leetcode: Add contains-duplicate-ii
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 7, 2023
1 parent 1e5f370 commit 8302fa6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions leetcode/0219.contains-duplicate-ii/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0219-contains-duplicate-ii"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
31 changes: 31 additions & 0 deletions leetcode/0219.contains-duplicate-ii/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be
// found in the LICENSE file.

pub fn contains_nearby_duplicate(nums: Vec<i32>, k: i32) -> bool {
let len = nums.len();
let k = k as usize;

for i in 0..(len - 1) {
for j in (i + 1)..len {
if nums[i] == nums[j] && j - i <= k {
return true;
}
}
}
false
}

fn main() {
let nums = vec![1, 2, 3, 1];
let k = 3;
assert!(contains_nearby_duplicate(nums, k));

let nums = vec![1, 0, 1, 1];
let k = 1;
assert!(contains_nearby_duplicate(nums, k));

let nums = vec![1, 2, 3, 1, 2, 3];
let k = 2;
assert!(!contains_nearby_duplicate(nums, k));
}

0 comments on commit 8302fa6

Please sign in to comment.