描述
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
解析
根据题意,只需要找出在 A 中出现次数最多的那个元素即可,使用内置的 Counter 统计之后即可找出答案。
解答
class Solution(object):
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
r = collections.Counter(A).most_common(1)
return r[0][0]
运行结果
Runtime: 204 ms, faster than 22.88% of Python online submissions for N-Repeated Element in Size 2N Array.
Memory Usage: 14.7 MB, less than 48.33% of Python online submissions for N-Repeated Element in Size 2N Array.
解析
根据题意,只需要找出在 A 中出现次数最多的那个元素即可,定义一个集合 a ,在遍历 A 的过程中,只要没有在 a 中出现就添加到 a ,如果出现过直接返回改元素即可。
解答
class Solution(object):
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
a = set()
for i in A:
if i in a:
return i
a.add(i)
return
运行结果
Runtime: 160 ms, faster than 88.95% of Python online submissions for N-Repeated Element in Size 2N Array.
Memory Usage: 14.2 MB, less than 92.55% of Python online submissions for N-Repeated Element in Size 2N Array.
原题链接:leetcode.com/problems/n-…
您的支持是我最大的动力