数组中重复的数字

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了数组中重复的数字脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任一一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1

 1 /**
 2  * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 3  *
 4  * 
 5  * @param numbers int整型维数 6  * @return int整型
 7  */
 8 function duplicate( numbers ) {
 9     // wrITe code here
10     if(!numbers.length){return -1;}
11     numbers.sort((a,b)=> a-b)
12     let res;
13     for(let i = 0;i<numbers.length;i++){
14         if(numbers[i]===numbers[i+1]){
15             res = numbers[i];
16             break;
17         }
18     }
19     return res;
20 }
21 module.exports = {
22     duplicate : duplicate
23 };
  • Map.has:返回一个bool值,用来表明map 中是否存在指定元素.
  • Map.set:为&nbsp;Map 对象添加或更新一个指定了键(key)和值(value)的(新)键值对。
 1 /**
 2  * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 3  *
 4  * 
 5  * @param numbers int整型一维数组 
 6  * @return int整型
 7  */
 8 function duplicate( numbers ) {
 9     // write code here
10     let map = new Map();
11     let res = -1;
12     for(let i = 0;i<numbers.length;i++){
13         if(map.has(numbers[i])){
14             res = numbers[i];
15             break;
16         }else{
17             map.set(numbers[i],true)
18         }
19     }
20     return res;
21 }
22 module.exports = {
23     duplicate : duplicate
24 };

脚本宝典总结

以上是脚本宝典为你收集整理的数组中重复的数字全部内容,希望文章能够帮你解决数组中重复的数字所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。