找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
思路:题目比较简单,有三种思路
第一种:
循环将值放入到字典中,如果下一个循环字典中有这个值,直接return
代码:
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
repeatdict = {}
for num in nums:
if num not in repeatdict:
repeatdict[num] = 1
else:
return num
第二种:
思路几乎一样,稍微耗时
代码:
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
count = collections.Counter(nums)
dic = dict(count)
for key,value in dic.items():
if value>1:
return key
break
思路三:
直接先进行排序,然后找到和左边或者和右边元素相同的元素,return出来










