题目

找出数组中重复的数字。

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

示例 1:

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

限制:

2 <= n <= 100000

答案1

  1. from typing import List
  2. class Solution:
  3. def findRepeatNumber(self, nums: List[int]) -> int:
  4. dic = {}
  5. for i in nums:
  6. if i not in dic:
  7. dic[i] = 0
  8. else:
  9. return i
  10. Solution().findRepeatNumber([2, 3, 1, 0, 2, 5, 3])

Note

哈希表

答案2

  1. from typing import List
  2. class Solution:
  3. def findRepeatNumber(self, nums: List[int]) -> int:
  4. nums = sorted(nums)
  5. tem = nums[0]
  6. for i in range(1, len(nums)):
  7. if nums[i] == tem:
  8. return nums[i]
  9. tem = nums[i]
  10. Solution().findRepeatNumber([2, 3, 1, 0, 2, 5, 3])

Note

先排序

参考

https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/solution/pythonti-jie-san-chong-fang-fa-by-xiao-xue-66/