题目
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
来源:力扣(LeetCode)
链接:[https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
题解
1、哈希表法,时间复杂度O(n)
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
repeatDict={}#创建空字典
for i in nums:#遍历数组
if i not in repeatDict:
repeatDict[i]=1#哈希函数,若某数组元素不在新字典里,则该元素哈希过后为1
else:
return i#若数组元素已存在,则返回该数组元素
2、先排序,后返回,时间复杂度O(nlogn)
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
nums.sort()
pre=nums[0]
for i in range(1,len(nums)):
if pre==nums[i]:
return pre
else:
pre=nums[i]