从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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志