题目地址:N-Repeated Element in Size 2N Array - LeetCode
Acceptance:73.3%
Difficulty:Easy
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大小的数组中,有N+1独特的元素,这些元素中的一个重复了N次。
找出这个元素
只要找出现次数大于等于2次的元素就行。
python代码:
class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
s=set()
for i in A:
if i not in s:
s.add(i)
else:
return i
java 代码:
class Solution {
public int repeatedNTimes(int[] A) {
Set<Integer> count = new HashSet();
for(int i:A){
if (count.contains(i)) {
return i;
}else {
count.add(i);
}
}
return 0;//没有return 0无法编译
}
}
如果想要O(1)的空间,做法如下:
class Solution {
public int repeatedNTimes(int[] A) {
for (int i = 2; i < A.length; ++i)
if (A[i] == A[i - 1] || A[i] == A[i - 2])
return A[i];
return A[0];
}
}