更多LeetCode题解
力扣中文网没有此题
My Solution
此题很简单,要注意的是对每一个元素的搜索,只要从它的后一个元素开始搜索就可以了,减少一些时间复杂度
C++
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
int res;
for (int i = 0; i < A.size() - 1; i++) {
if (find(A.begin() + i + 1, A.end(), A[i]) != A.end()) {
res = A[i];
break;
}
}
return res;
}
};
通过容器,来调用容器的count方法,很方便,C++的unordered_map
也有类似的功能。
java
class Solution {
public int repeatedNTimes(int[] A) {
Map<Integer, Integer> count = new HashMap();
for (int x: A) {
count.put(x, count.getOrDefault(x, 0) + 1);
}
for (int k: count.keySet())
if (count.get(k) > 1)
return k;
throw null;
}
}
python
class Solution(object):
def repeatedNTimes(self, A):
count = collections.Counter(A)
for k in count:
if count[k] > 1:
return k
Approach 2
此序列满足:
必存在一个长度为4的子序列,子序列内有重复元素。
java
class Solution {
public int repeatedNTimes(int[] A) {
for (int k = 1; k <= 3; ++k)
for (int i = 0; i < A.length - k; ++i)
if (A[i] == A[i+k])
return A[i];
throw null;
}
}
python
class Solution(object):
def repeatedNTimes(self, A):
for k in xrange(1, 4):
for i in xrange(len(A) - k):
if A[i] == A[i+k]:
return A[i]
class Solution:
def repeatedNTimes(self, A):
for i in range(len(A)):
if A[i - 1] == A[i] or A[i - 2] == A[i]:
return A[i]