Contains duplicate Problem
March 23, 2023
Problem
Given an array of integers, write a function that determines whether the array contains any duplicates. Your function should return true
if any element appears at least twice in the array, and it should return false
if every element is distinct.
Example
-
For
a = [1, 2, 3, 1]
, the output should be
solution(a) = true
.There are two
1
s in the given array. -
For
a = [3, 1]
, the output should be
solution(a) = false
.The given array contains no duplicates.
Solution
Using HashSet
The solution is straightforward, create hash map to check if the array is duplicate or not.
use std::collections::HashSet;fn solution(a: Vec<i32>) -> bool { let mut set= HashSet::new(); for i in a{ if !set.insert(i){ return true; } } false}
Or short version implementation above
use std::collections::HashSet;fn solution(a: Vec<i32>) -> bool { let mut set = HashSet::new(); a.into_iter().any(|x| !set.insert(x))}
Using dedup function
This solution not using hash set but use sort
and dedup
fn solution(mut a: Vec<i32>) -> bool { let original_length = a.len(); a.sort(); a.dedup(); a.len() != original_length}
See the vector docs (opens in a new tab) for the details internal function and how to use it.