找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思考过程:把长度为n数组中的每个数据读取出来,然后在一个标记索引上标记当前对象出现的次数,将标记次数大于1的输出出来。
from typing import List
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
objIdx=[0]*len(nums)
for i in nums:
objIdx[i]=objIdx[i]+1 # 对每个对象进行计数
moreThanOne=objIdx>1 # 出现大于一次的对象逻辑值
return objIdx(moreThanOne).index # 等于1的索引即重复的对象
NOTE:由于长时间没有使用python,一些基本语法忘记,大概是这个意思。但是根据大于号来得到重复对象的运算,不能够进行,报错TypeError: '>' not supported between instances of 'list' and 'int'。另外,任意重复数字,这个没有注意到。
评论区的参考:利用哈希表,时间O(n),空间O(n)
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