1. 题目介绍
《剑指offer》第3题 - 找出数组中重复的数字
在一个长度为n的数组里所有的数字都在0~n-1之间, 数组可能存在重复数字, 找出这个数组中重复的数字中的任意一个;
比如输入长度为7的数组{2, 3, 1, 0, 2, 5, 3}, 对应重复数字为2, 3;
1. 利用哈希表是最常见的解法, 但是需要维护一个空间复杂度为o(n)的哈希表;
2. 利用哈希表解法, 无法用到题中的条件"长度为n的数组里所有的数字都在0~n-1之间";
3. 常常需要考虑到数组为空,数组包含特殊元素等,使程序更鲁棒;
2. Python实现
def find_duplicates_num_1(List):
""" 法一
利用哈希表, o(n)时间复杂度, o(n)空间复杂度;
key = 数组中的元素, value = 元素出现的次数;
"""
num_cnt = {}
for num in List:
num_cnt[num] = num_cnt.get(num, 0) + 1
if num_cnt[num] > 1:
return num
return False
def find_duplicates_num_2(List):
""" 法二: o(n)时间复杂度, o(1)空间复杂度 """
# 空串
if len(List) == 0:
raise(Exception("List has no number."))
# List中包含0~n-1之外的数字
if max(List) >= len(List) or min(List) < 0:
raise(Exception("List's number must be in 0~n-1."))
length = len(List)
for i in range(length):
if List[i] < i:
return List[i], i
while i != List[i]:
temp = List[i]
List[i] = List[temp]
List[temp] = temp
return False
if __name__ == "__main__":
result, i = find_duplicates_num_2([])
3. C++实现