50.数组中重复的数字
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
记录
方法一:
字典
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
d = {}
for i in numbers:
if i not in d:
d[i] = 1
else:
d[i] += 1
for k,v in d.items():
if v > 1:
duplication[0] = k
return True
return False
方法二:
因为数组长度为n, 整数范围为0~n-1, 所以我们可以直接用这个数组来标记已经出现过的数, 如果再次在某次标记的时候又第二遇到, 那肯定就是有重复了 。
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
cur = 0
while cur < len(numbers):
if numbers[cur] == cur:
cur += 1
continue
if numbers[cur] == numbers[numbers[cur]]:
duplication[0] = numbers[cur]
return True
temp = numbers[cur]
numbers[cur] = numbers[numbers[cur]]
numbers[temp] = temp
return False