从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
热门推荐
2 祝福语情人节简短
10 送花顾客祝福语简短的话
11 可爱小狗祝福语简短
12 感谢朋友的祝福语简短
13 生日酒宴诗句祝福语简短
14 狗年祝福语简短的英文
15 祝福语2026简短对家人
16 好友搞笑留言祝福语简短
17 新年喝酒祝福语大全简短
18 拜年同事祝福语大全简短