From 1e5f3708bd9d873490a9ac9548788d8b5557428b Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Thu, 7 Dec 2023 21:15:13 +0800 Subject: [PATCH] leetcode: Add contains-duplicate --- leetcode/0217.contains-duplicate/Cargo.toml | 7 +++ leetcode/0217.contains-duplicate/src/main.rs | 46 ++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 leetcode/0217.contains-duplicate/Cargo.toml create mode 100644 leetcode/0217.contains-duplicate/src/main.rs diff --git a/leetcode/0217.contains-duplicate/Cargo.toml b/leetcode/0217.contains-duplicate/Cargo.toml new file mode 100644 index 00000000..f56ce87b --- /dev/null +++ b/leetcode/0217.contains-duplicate/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0217-contains-duplicate" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/leetcode/0217.contains-duplicate/src/main.rs b/leetcode/0217.contains-duplicate/src/main.rs new file mode 100644 index 00000000..bc384d61 --- /dev/null +++ b/leetcode/0217.contains-duplicate/src/main.rs @@ -0,0 +1,46 @@ +// Copyright (c) 2023 Xu Shaohua . 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) -> 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) -> 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)); +}