961. N-Repeated Element in Size 2N Array*
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/
题目描述
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
C++ 实现 1
使用哈希表, 注意 A
中的数据除了那个出现 N
次的元素, 其他数据都是 unique 的. 下面的代码最多遍历 N
次. 而采用 C++ 实现 2
中的代码, 可能要遍历 2N
次.
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
unordered_set<int> record;
for (auto &c : A) {
if (record.count(c)) return c;
record.insert(c);
}
return -1;
}
};
C++ 实现 2
相比 C++ 实现 1
中的代码更慢. 用哈希表统计个数.
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
unordered_map<int, int> record;
int res = A[0];
for (auto &c : A) {
record[c] ++;
if (record[c] == A.size() / 2) {
res = c;
break;
}
}
return res;
}
};