Section titled Problem
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 besolution(a) = true
.There are two
1
s in the given array.For
a = [3, 1]
, the output should besolution(a) = false
.The given array contains no duplicates.
Section titled Solution
Solution
Section titled Using%20HashSet
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))
}
Section titled Using%20dedup%20function
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 for the details internal function and how to use it.