英文题目:
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
中文题目解释:
在一个
A
大小的数组中2N
,有N+1
独特的元素,这些元素中的一个重复N次。重复返回元素
N
。例1:
输入:[1,2,3,3] 输出:3
例2:
输入:[2,1,2,5,3,2] 输出:2
例3:
输入:[5,1,5,2,5,3,5,4] 输出:5
注意:
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length
为偶数
解析:
遍历数组A将值放入集合中,放入集合之前判断集合中是否存在相同值,若已存在则返回该值
提交结果:
class Solution {
public int repeatedNTimes(int[] A) {
Set s=new HashSet();
for (int i:A) {
if(s.contains(i)){
return i;
}else{
s.add(i);
}
}
return 0;
}
}