Skip to content

Commit

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

[dependencies]
46 changes: 46 additions & 0 deletions leetcode/0217.contains-duplicate/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// 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_duplicate(nums: Vec<i32>) -> bool {
assert!(!nums.is_empty());
let len = nums.len();
for i in 0..(len - 1) {
for j in (i + 1)..len {
if nums[i] == nums[j] {
return true;
}
}
}
false
}

pub fn contains_duplicate2(nums: Vec<i32>) -> bool {
assert!(!nums.is_empty());
let mut nums = nums;
nums.sort();
let len = nums.len();
for i in 0..(len - 1) {
if nums[i] == nums[i + 1] {
return true;
}
}
false
}

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

let nums = vec![1, 2, 3, 4];
assert!(!contains_duplicate(nums));
let nums = vec![1, 1, 1, 3, 3, 4, 3, 2, 4, 2];
assert!(contains_duplicate(nums));

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

0 comments on commit 1e5f370

Please sign in to comment.