题目描述
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.
在大小为2N的数组A中,有N+1个唯一元素,其中一个元素恰好重复N次。返回重复N次的元素。
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
思路
遍历数组,将数组中的元素存入HashMap中。若不存在该元素则计数1,存在则计数再加1
class Solution {
public int repeatedNTimes(int[] A) {
Map<Integer, Integer> count = new HashMap();
for (int x: A) {
count.put(x, count.getOrDefault(x, 0) + 1);
}
for (int k: count.keySet())
if (count.get(k) > 1)
return k;
throw null;
}
}