class Solution: def duplicate(self , numbers ): # write code here # dic = {} # 方法1:使用dic字典,如果存在则返回,不存在则标记,空间复杂度o(n) # if not numbers: # return -1 # for i in range(len(numbers)): # if numbers[i] in dic: # return numbers[i] # else: # dic[numbers[i]] =1 if not numbers: # 方法二:空间复杂度o(1),遍历原数组,将原数组的值作为数组的索引,如果大于0表示第一次访问,然后取反,如果小于0表示已经访问过了。 return -1 for i in range(len(numbers)): if numbers[abs(numbers[i])]<0: return abs(numbers[i]) else: numbers[abs(numbers[i])] = -numbers[abs(numbers[i])]