题目: 找出数组中重复的数字(剑指 Offer 03)
描述:
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
==================================================
这道题在考察什么?
考察点:考察和出题者的沟通能力?
对该题解法的要求是什么?时间复杂度和空间复杂度的限制
要求1:时间效率优先,可以忽略空间复杂度;
解法如下:
直接用字典大法就搞定了!
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 字典遍历方法
result ={}
for tmp in nums:
if tmp not in result:
result[tmp] = 1
else:
return tmp
要求2:空间复杂度为1,且可以对原数组进行修改;
解法如下:
使用位置交换法,注意特殊位置的判盘;
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 位置交换法
size = len(nums)
for index in range(0, size):
# 特殊情况判断
if index == nums[index]:
continue
if nums[index]==nums[nums[index]]:
return nums[index]
else:
tmp = nums[index]
nums[index] = nums[tmp]
nums[tmp] = tmp
return -1
要求3:如果要求空间复杂度为1,且不可以对原数组进行修改?
这种情况的解法就比较复杂了;应该是要借助二分查找了;
但是我认为这就有些hard;可以了解下思路;但是未必写代码;