存在重复元素,每日一题

172 阅读1分钟

217. 存在重复元素

Difficulty: 简单

给定一个整数数组,判断是否存在重复元素。

如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

示例 1:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

Solution

Language: java

class Solution {
    //像判断是否重复这种题,毫无疑问,首先想到的就是借助Set
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet();
        for(int a : nums)
        {
            if(!set.add(a))
            {
                return true;
            }
        }
        return false;
    }
}

进行优化处理

class Solution {

    public int repeatedNTimes(int[] A) {
        if(A == null || A.length < 4) return -1;
        Set<Integer> set = new HashSet();
        //有N+1个不同的元素,只有一个重复了N次,那也就是说其他的元素都是互不相同的
        for(int a : A)
        {
            if(!set.add(a))
            {
                return a;
            }
        }
        return -1;
    }
}