从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 好听的元旦简短祝福语