难度:Easy

题目描述:

English Version:
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

中文:
给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

测试样例

Example1:

Input: [1, 2, 3, 1]
Output: true

Example2:

Input: [1, 2, 3, 4]
Output: false

Example3:

Input: [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
Output: true

解题思路

相信大多数人和笔者一样,第一反应是暴力搜索法,即通过两层循环嵌套实现一个时间复杂度为的解法。不过在经过尝试后发现,每次运行都会超时(不论是Java, C, C++, 还是Python),这时候就应该考虑重新设计算法。

判断是否有重复元素,可以借助集合set的特性:

集合中不允许有重复的元素。当待插入的元素已经出现在集合中
时,会将其自动忽略掉。

为此,我们可以基于目标数组创建一个集合,之后比较该集合和原始数组包含元素的数量。若是集合中的元素数量较少,则说明有重复的元素,直接返回true即可;反之则返回false.

Java代码

class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> result = new HashSet<>();
        for (int i : nums) {
            result.add(i);
        } 
        return result.size() < nums.length ? true : false;
    }
}