961. 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

解答

这个题目是说,给一个长度为2N的数组,里面有N+1个元素都是唯一的,有N个重复的元素。请返回给我这个重复的元素。

也就是说唯一的元素计数都是1,有一个元素计数大于1,那么只要找出这个计数大于1的就好了。

可以使用一遍循环,map来记录每个数出现的count,一旦出现大于1的,就return。

public int repeatedNTimes(int[] A) {
    Map<Integer, Integer> count = new HashMap<>();

    for (int a : A) {
        count.put(a, count.getOrDefault(a, 0) + 1);
        if (count.get(a) > 1) {
            return a;
        }
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章