题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
这道题可以用额外数组来做,但是它有特点,在长度为n的数组中没有超过n-1的数字,所以可以用数字的索引来做。具体做法是,用数字当做索引来访问,访问过就+len(n),如果访问到后面发现这个索引的数曾经被访问过就是重复的数。
以[2,1,3,1,4]为例,数组长度5
n[0]=2,令n[n[0]]=n[2]+5, [2,1,8,1,4]
n[1]=1,令n[1]+5, [2,6,3,1,4]
n[2]=3,令n[3]+5, [2,6,3,6,4]
n[3]=6>5 ,index=6-5=1, n[1]=6>5,返回
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
n=numbers
d=duplication
tmp=len(n)
for i in range(tmp):
index=n[i]
if index>=tmp:
index=index-tmp
if n[index]>=tmp:
duplication[0]=index
return True
n[index]+=tmp
return False