题解 | #数组中重复的数字#
数组中重复的数字
https://www.nowcoder.com/practice/6fe361ede7e54db1b84adc81d09d8524
题目
描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1
数据范围:0\le n \le 10000 \0≤n≤10000
进阶:时间复杂度O(n)\O(n) ,空间复杂度O(n)\O(n)
示例1
输入:
[2,3,1,0,2,5,3]复制
返回值:
2复制
说明:
2或3都是对的
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @return int整型
*/
function duplicate( numbers ) {
// write code here
let set = new Set();
for(let i=0 ;i<numbers.length;i++){
if(set.has(numbers[i])){
return numbers[i];
}else{
set.add(numbers[i])
}
}
return -1;
}
module.exports = {
duplicate : duplicate
};
思路
创建一个新的数组set
使用set.has函数与set.add函数
遍历numbers
如果numbers【i】的值与set数值中的任意一个值相同则函数结果为true,返回numbers【i】的值
都不相同则返回false,set.add函数将numbers【i】的值存到数组set中。