版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88061513
Description:
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次的那个元素;
解法:我们需要统计哪个元素的次数为N次,可以考虑利用哈希表来实现,这样,我们在遍历数组时,记录元素出现的次数,当此元素出现的次数已经为N时,那么这个元素就是最终的答案(因为数组中出现次数为N的元素是唯一的);
Java
class Solution {
public int repeatedNTimes(int[] A) {
Map<Integer, Integer> frequency = new HashMap<>();
int res = A[0];
for (int x: A) {
frequency.put(x, frequency.getOrDefault(x, 0) + 1);
if (frequency.get(x) == A.length / 2) {
res = x;
break;
}
}
return res;
}
}