You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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];
}
};
In a array
A
of size2N
, there areN+1
unique elements, and exactly one of these elements is repeatedN
times.Return the element repeated
N
times.Example 1:
Example 2:
Example 3:
Note:
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length
is even这道题说是有一个长度为 2N 的数组A,里面有 N+1 个不同的数,而且有一个数字正好重复了N次,让找出这个重复了N次的数字。并不是一道难题,可以直接使用一个 HashMap 来统计每个数字出现的个数,只要某个数字出现了 N 次即符合题意返回即可。但这里我们可以进一步的优化一下,由于只有一个数字有重复,其他的都是不重复的,所以只要发现某个数字出现次数大于1次,就可以直接返回了,参见代码如下:
解法一:
由于这道题数组的特殊性,有一半的数字是重复的,所以只要某个相连的三个数字出现重复数字,就一定为所求。这里为了避免 index 溢出,从第三个数字开始遍历,每次找和前两个数字是否出现重复,若有重复则直接返回该数字。但也有遍历完了没有出现重复的情况,只有 [x, x, y, z] 或 [x, y, z, x] 这两种情况,直接返回第一个数字即可,参见代码如下:
解法二:
Github 同步地址:
#961
参考资料:
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/208317/C%2B%2B-2-lines-O(4)-or-O-(1)
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/208563/JavaC%2B%2BPython-O(1)-Solution
LeetCode All in One 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: