英文題目:
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;
}
}