重复 N 次的元素,字节题库

268 阅读1分钟

961. 重复 N 次的元素

Difficulty: 简单

在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。

返回重复了 N 次的那个元素。

示例 1:

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

示例 2:

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

示例 3:

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

提示:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length 为偶数

Solution

首先看到重复的元素,第一反应就是用Set,然后要统计元素出现的次数,每一个元素出现的次数都记录下来,很自然的就想到了用HashMap来解决,所以有了下面的解法; Language: java

class Solution {

    //比如我现在用HashMap来做

    public int repeatedNTimes(int[] A) {
        if(A == null || A.length < 4) return -1;
        Map<Integer , Integer> map = new HashMap();
        for(int a : A)
        {
            map.put(a , map.getOrDefault(a , 0) + 1);
        }
        //然后再对map进行迭代判断
        for(Map.Entry<Integer , Integer> entry : map.entrySet())
        {
            int value = entry.getValue();
            if(value >= A.length / 2 )
            {
                return entry.getKey();
            }
        }
        return -1;
    }
}

但很不幸的是,这种方式,只超过了16%的提交记录,看来还是有很大的优化空间;

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