Contains duplicate Problem

0 min read Tweet this post

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 1s in the given array.

  • For a = [3, 1], the output should be
    solution(a) = false.

    The given array contains no duplicates.

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))
}

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.

rust cp