21 N-Repeated Element in Size 2N Array

关注 每天一道编程题 专栏,一起学习进步。

题目

In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times.

Example 1:

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

Example 2:

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

Example 3:

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

Note:

4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even

分析

题意:长度为2N的数组,其中N+1个都是唯一的,有一个重复N次的数,将其找出来。

算法:
创建一个长度为10000的数组tmp
遍历所给数组A,将tmp[i]++
如果tmp[i]==A.length/2,A返回

解答

class Solution {
    public int repeatedNTimes(int[] A) {
        int [] tmp =new int[10000];
        for(int i:A){
            tmp[i]++;
            if(tmp[i]==A.length/2){
                return i;
            }
        }
        return -1;
    }
}

上述算法复杂度太高
看看评论区的解答

class Solution {
        public int repeatedNTimes(int[] A) {
        int[] count = new int[10000];
        for (int a : A)
            if (count[a]++ == 1)
                return a;
        return -1;
    }
}

我的算法里面是判断出现N次,但是实际上,只要出现2次,则该数就是目标,因为2N个数=N+1的唯一和N个重复(这多了一个,是因为多的那个就是重复N次的)
两种算法的思路都是一样的。

全部评论

相关推荐

lllllkin:感觉可以精简到一页简历,有些排版感觉不是必须的。 时间线越早的,你自己越熟悉的放前面。描述可以更精简些,一些问题解决感觉可以不用写具体技术栈,卖个关子,等面试官问。
点赞 评论 收藏
分享
Twilight_mu:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务