从JavaScript中的数组返回第一个重复的数字
我们需要编写一个函数,该函数返回数组中至少出现两次的第一个元素的索引。如果没有元素出现多次,我们必须返回-1。条件是我们必须在恒定的空间中执行此操作(即,不使用额外的内存)。
让我们为这个问题设计解决方案。我们将使用for循环遍历数组,并使用Array.prototype.lastIndexOf()方法检查重复项。
示例
const firstDuplicate = arr => {
for(let i = 0; i < arr.length; i++){
if(arr.lastIndexOf(arr[i]) !== i){
return i;
};
};
return -1;
}
console.log(firstDuplicate([3, 5, 6, 8, 5, 3])); // 0
console.log(firstDuplicate([0, 1, 2, 3, 4, 4, 5])); // 4
console.log(firstDuplicate([0, 1, 1, 2, 3, 4, 4, 5])); // 1
console.log(firstDuplicate([0, 1, 2, 3, 4, 9, 5])); // -1输出结果
控制台中的输出将为-
0 4 1 -1
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短