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
這道題說是有一個長度為 2N 的數組A,里面有 N+1 個不同的數,而且有一個數字正好重復了N次,讓找出這個重復了N次的數字。並不是一道難題,可以直接使用一個 HashMap 來統計每個數字出現的個數,只要某個數字出現了 N 次即符合題意返回即可。但這里我們可以進一步的優化一下,由於只有一個數字有重復,其他的都是不重復的,所以只要發現某個數字出現次數大於1次,就可以直接返回了,參見代碼如下:
解法一:
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
int n = A.size();
unordered_map<int, int> numCnt;
for (int num : A) {
if (++numCnt[num] > 1) return num;
}
return -1;
}
};
由於這道題數組的特殊性,有一半的數字是重復的,所以只要某個相連的三個數字出現重復數字,就一定為所求。這里為了避免 index 溢出,從第三個數字開始遍歷,每次找和前兩個數字是否出現重復,若有重復則直接返回該數字。但也有遍歷完了沒有出現重復的情況,只有 [x, x, y, z] 或 [x, y, z, 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[0];
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/961
參考資料:
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/