avatar

Catalog
面试题 -- 数组中重复的数字

题目描述

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3

剑指offer03 — 数组中重复的数字

  • 遍历整个数组,当这个数字没有出现过哈希表的时候将其加入进去,如果在哈希表中则直接返回即可
  • 时间复杂度O(n),空间复杂度O(n)
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
    if not nums:
        return nums
    dic = {}
    for i in nums:
        if i in dic:
            return i
        else:
            dic[i] = 0
    return 0
Author: kim yhow
Link: http://yoursite.com/2020/03/06/面试题01/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶