题目
哈希表
列表中除了重复的元素其余的都只出现一次
我们将出现的元素储存
当元素再次出现时输出
代码
class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
found = set()
for num in nums:
if num in found:
return num
found.add(num)
# 不可能的情况
return -1
随机数
从nums中随机抽取2个下标
两个数相等且下标不相等
我们输出这个数
代码
class Solution:
def repeatedNTimes(self , nums:List[int]) -> int:
n = len(nums)
while True:
x, y = \random.randrange(n),random.randrange(n)
if x != y and nums[x] == nums[y]:
return nums[x]
总结
一开始审题不清
以为不止一个元素重复
导致使用了效率更慢的计数及查找
以后加强审题方面