题目:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1
思路:
1、先确定输入检测,数据范围:0 ≤ 数组长度 ≤ 10000 ,0≤ 数组中元素 ≤ 数据长度-1,输入数据不对则输出-1;
2、对输入数组进行遍历,使用新列表存储,判断数组中的元素是否已经存在新列表中,若是存在则输出该元素,若不存在则遍历结束后输出-1。
from typing import List
class Solution:
def duplicate(self, numbers: List[int]) -> int:
n_list = []
if 0 <= len(numbers) <= 10000:
for num in numbers:
if 0 <= num <= len(numbers) -1:
if num not in n_list:
n_list.append(num)
else:
return num
else:
break
n_list.clear()
return -1