找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
法一:将数组排序,然后依次看相邻元素是否相同,有相同直接return
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
pre = nums[0]
n = len(nums)
for index in range(1,n):
if pre == nums[index]:
return pre
pre = nums[index]
法二:字典
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