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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章