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
题意:给出一长度为2*n的数组,其中有n个元素仅出现一次,一个元素X出现了n次,求出元素X。
方法一:哈希思想,记录每个元素出现的次数,遇到一个出现2次的即找到,该方法需要开辟足够大的内存。
方法二:因为元素X出现了n次,则必会出现要么两个X紧邻,要么中间相隔一个其他元素的情况。对每个位置判断即可。
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
for(int i=2;i<A.size();i++){
if(A[i]==A[i-1]||A[i]==A[i-2])
return A[i];
}
return A[A.size()-1];
}
};