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
Analyse
数组A
一共2N
个数,其中一个数出现了N
次,整个数组A
中共有N+1
个不一样的数
很容易用map写出一个版本,使用map计数,返回数量为N的那个数
时间复杂度 \(O(n)\),n是A的size()
空间复杂度 \(O(n)\),n是A的size()
int repeatedNTimes(vector& A) {
map _map;
for(int val : A)
{
if (++_map[val] == (A.size()/2))
{
return val;
}
}
return 0;
}
再进一步,要找到重复出现N
次的那个数,由于其他数都是唯一的,只要找到重复出现2次的数就行了
这个比之前的版本快那么一点点,本质上差异并不大
时间复杂度 \(O(n)\),n是A的size()
空间复杂度 \(O(n)\),n是A的size()
int repeatedNTimes(vector& A) {
map _map;
for(int val : A)
{
if (++_map[val] == 2)
{
return val;
}
}
return 0;
}
另一种办法是比较,从LeetCode上看到的
If we ever find a repeated element, it must be the answer. Let's call this answer the major element.
Consider all subarrays of length 4. There must be a major element in at least one such subarray.
This is because either:
- There is a major element in a length 2 subarray, or;
- Every length 2 subarray has exactly 1 major element, which means that a length 4 subarray that begins at a major element will have 2 major elements.
Thus, we only have to compare elements with their neighbors that are distance 1, 2, or 3 away.
只要找到一个重复的值,这个值就是要找的
至少有一个长度为4的子序列中存在重复的值
LeetCode的讨论区回答说需要检查的子序列的长度可以减小到3
时间复杂度 \(O(n)\),n是A的size()
空间复杂度 \(O(1)\)
int repeatedNTimes(vector& A) {
for(int i = 0; i < A.size()-2; i++)
{
if(A[i] == A[i+1] || A[i] == A[i+2])
{
return A[i];
}
}
return A[A.size()-1];
}
Reference
1.https://leetcode.com/problems/n-repeated-element-in-size-2n-array/solution/